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.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details