Loading…
Contains Duplicate is a easy coding interview question covering arrays, hash maps — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Given an integer array nums, return true if any value appears at least twice, false if all elements are distinct.
Example: [1,2,3,1] -> true Example: [1,2,3,4] -> false
Can you solve it in O(n) time?
Try it yourself first
In an interview you'd get about 15 minutes for a easy question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Hash set approach: insert elements one by one; if an element is already in the set, return true. O(n) time and space. Trade-off: sort-and-scan is O(n log n) time but O(1) space.
| 1 | def contains_duplicate(nums: list[int]) -> bool: |
| ▶ | seen = set() |
| 3 | for num in nums: |
| 4 | if num in seen: |
| 5 | return True |
| 6 | seen.add(num) |
| 7 | return False |
| 8 | |
| 9 | # Pythonic one-liner (no early exit): |
| 10 | # return len(set(nums)) != len(nums) |
Init seen={}.
Key Insights
A full interview loop is more than one round. These are the others, each with what is on the site for it.