Does any number show up twice? Walk the list once with a set of values you've already seen, and stop the moment one repeats.
▼The problem
Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
Examples: [1, 2, 3, 1] → true (the first and last are both 1); [1, 2, 3, 4] → false.
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return FalseTRY IT ON LEETCODE ▶The solution
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return FalseTranscript
Contains Duplicate. You get an array of numbers. Return true if any value shows up at least twice, false if every value is distinct. Picture a border desk: each number is a visitor, and we check if anyone comes through twice.
Take one, two, three, one. The first and last are both one, so the answer is true. Now take one, two, three, four. Every value is different: false.
The naive way compares every pair. Four numbers make six pairs; n numbers make about n squared over two. A million numbers means half a trillion checks. Sorting first helps: equal values land side by side; one scan of adjacent pairs finds them, in n log n time. But can we do it in one pass?
Yes, with a memory. Keep a set of every value you've seen, like a book of stamps. A set answers "have I seen this?" in constant time on average, however big it grows. Check each number as it arrives. If it's in the set, stop: that's a duplicate. If not, stamp it in and move on.
Let's run one, two, three, one. One: is it in the set? No, the set is empty, so stamp it in. Two is new, stamp it. Three is new, stamp it. Then one again. The set already holds a one. Duplicate! Return true, right away. On a longer array, we'd stop right here.
Now one, two, three, four. Each is new, so all four get stamped in. The loop ends without a match, so we return false. This time the set held every value.
In code, start with an empty set. Loop over the numbers. If a number is already in the set, return true. Otherwise, add it. If the loop finishes with no repeat, return false.
Each number is checked once, and each lookup takes constant time on average, so the time is O of n. With no repeats, the set holds all n values, so the space is O of n too. We trade memory for speed.
Remember what you've seen, and stop at the first repeat. That's Contains Duplicate.