217. Contains Duplicate
easyGiven an integer array, return true if any value appears at least twice. The cleanest one-line hash-set problem — and the cleanest demonstration of why a set beats nested loops on duplicate-detection.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Examples
Example 1
nums = [1,2,3,1]trueExample 2
nums = [1,2,3,4]falseExample 3
nums = [1,1,1,3,3,4,3,2,4,2]trueSolve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Brute-force nested loop is O(n^2). What data structure decides 'have I seen this before?' in O(1)?
Hint 2
A hash set. Walk the array once; if num is in the set, return true.
Hint 3
Equivalent slick one-liner: return len(set(nums)) != len(nums) — but the early-exit hash-set version is faster in the duplicate-heavy case.
Solution approach
Reveal approach
Maintain a hash set of seen values. Walk the array once; for each num, if num is already in the set, return true; otherwise insert it. After the loop, return false. The early exit saves you from scanning past the first duplicate. The slick alternative len(set(nums)) != len(nums) is one line but always processes the whole array — no early exit. Both are O(n) time and O(n) space. Sorting and checking adjacent pairs is O(n log n) time with O(1) extra space — useful if memory is constrained.
Complexity
- Time
- O(n)
- Space
- O(n)
Related patterns
- hash-set
- sorting
Related problems
- 219. Contains Duplicate II
- 220. Contains Duplicate III
- 136. Single Number
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
- Apple
More Hash Tables practice problems
- 49. Group Anagrams
- 128. Longest Consecutive Sequence
- 167. Two Sum II - Input Array Is Sorted
- 202. Happy Number
- 205. Isomorphic Strings
- 242. Valid Anagram
- 290. Word Pattern
- 347. Top K Frequent Elements