Junior
Detailed answer
Arrays & Hashing
DSA & Coding Interviews
How would you solve Contains Duplicate?
Short answer: Insert elements into a HashSet while scanning. If an insert fails (already present), return true. Sorting and comparing neighbors also works in O(n log n) with O(1) extra space if sorting in place is allowed.
Sample solution
C#
bool ContainsDuplicate(int[] nums) {
var seen = new HashSet<int>();
foreach (int n in nums)
if (!seen.Add(n)) return true;
return false;
}
Complexity
HashSet: Time O(n), Space O(n). Sort: Time O(n log n), Space O(1)/O(n).
Common follow-ups
- Contains Duplicate II (distance ≤ k)
- Contains Duplicate III (value range)
Ask whether O(1) space matters — that steers you to sorting vs hashing.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png