Problem Statement
Contains Duplicate
You are given an array of whole numbers called nums. An array is just a list of items in order. Your job is to answer one yes-or-no question: does any number show up more than once? If even a single number repeats, return true. If every number is different from all the others, return false.
Translate the prompt
Given `nums`, return true when there are two different indices i and j with `nums[i] == nums[j]`. Return false only if every value is distinct.
Signals to notice
Brute force first
Compare every pair of indices i and j: O(n²). Sorting and checking neighbors also finds duplicates, but costs O(n log n) and changes the order unless you copy first.
The key insight
At each index i, you only need to know whether `nums[i]` has appeared before. A set remembers all earlier values, so the duplicate check becomes one lookup per element.
Trace it on nums=[1,2,3,1]
i=0 nums[i]=1 seen={} 1 seen before? no -> add seen={1}
i=1 nums[i]=2 seen={1} 2 seen before? no -> add seen={1,2}
i=2 nums[i]=3 seen={1,2} 3 seen before? no -> add seen={1,2,3}
i=3 nums[i]=1 seen={1,2,3} 1 seen before? YES -> return trueWhat must stay true
Before checking index i, `seen` contains exactly the distinct values from `nums[0..i)`. That means `nums[i] in seen` is the same as "this value appeared earlier."
Shape of the loop
seen = set() for i in range(len(nums)): if nums[i] in seen: return true seen.add(nums[i]) return false
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Adding `nums[i]` to the set before checking it. The check must ask about earlier values only; after you add the current value, the set no longer represents `nums[0..i)`.