Contains Duplicate
LeetCode 217 · Easy · solution, intuition & step-by-step walkthrough
A set turns 'have I seen this before?' into O(1).
This is how I solved Contains Duplicate (LeetCode 217), an easy problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code and the 3 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
A duplicate means some value appears twice. Comparing all pairs works but is quadratic; sorting puts equal values next to each other; a set remembers what you've seen so any repeat is caught the moment it appears.
Approach
- 1
Brute force: compare every pair.
- 2
Sort: equal values become neighbours, so compare each element to the previous one.
- 3
Set: add each number; if it's already present, return True.
How I solved it · from first idea to final
Check every pair.
Duplicates end up adjacent.
Return on the first repeat.
Brute force pairsPythonO(n²) time · O(1) space
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
for i in range(len(nums)):
for j in range(i):
if nums[i]==nums[j]:
return True
return FalseSort + neighboursPythonO(n log n) time · O(1) extra
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(1,len(nums)):
if nums[i]==nums[i-1]:
return True
return FalseHash setPythonO(n) time · O(n) space
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return FalseContains Duplicate — FAQ
What is the intuition behind Contains Duplicate?
A duplicate means some value appears twice. Comparing all pairs works but is quadratic; sorting puts equal values next to each other; a set remembers what you've seen so any repeat is caught the moment it appears.
How do you solve Contains Duplicate (LeetCode 217)?
1. Brute force: compare every pair. 2. Sort: equal values become neighbours, so compare each element to the previous one. 3. Set: add each number; if it's already present, return True.
What is the time and space complexity of Contains Duplicate?
Time: O(n). Space: O(n). (Accepted approach: Hash set.)
What are common mistakes in Contains Duplicate?
Sorting mutates the input — fine here, but worth noting.
Is there more than one way to solve Contains Duplicate?
Brute force pairs (O(n²) time · O(1) space): Check every pair. Sort + neighbours (O(n log n) time · O(1) extra): Duplicates end up adjacent. Hash set (O(n) time · O(n) space): Return on the first repeat.