Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Hash Map / Set High frequency Solution Available Practice Mode

Contains Duplicate LeetCode Solution

Tags: #Array #Hash Table #Sorting

Approach Summary

Add each element to a Set; return true the moment a duplicate is found.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Hash Map / Set Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.

Framework: Hash Map / Set • Interview Prep: Tested at FAANG • Explore all Hash Map / Set problems & invariants →

How to Recognize This Pattern

  • Existence check across all previous elements
  • Set is O(1) lookup vs O(n) scan

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

Array Hash Table Sorting

Frequently Asked Questions

What is the optimal time and space complexity for Contains Duplicate?
The optimal solution for Contains Duplicate achieves O(n) runtime complexity and requires O(n) auxiliary space. Checking membership and inserting into a hash set takes O(1) average time. In the worst case where all elements are unique, we insert all n items, yielding O(n) time and O(n) auxiliary space.
How do I identify that Contains Duplicate requires the Hash Map / Set pattern?
In technical interviews, look for key problem signals: Existence check across all previous elements; Set is O(1) lookup vs O(n) scan. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Hash Map / Set strategy.
What critical edge cases must be handled in Contains Duplicate?
Essential edge cases to verify include: Single-element array (always false); Array with all identical elements; Negative and positive numbers mixed; Large arrays with duplicate at the very start or end. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Contains Duplicate?
Contains Duplicate is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Google, Apple.
Buy me a coffee
Daily Practice
0/0