Contains Duplicate

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Contains Duplicate

Approach

Iterate through the array, adding each element to a Set. Before adding, check if the element already exists in the Set. If it does, a duplicate has been found. If the loop completes without finding a duplicate, return false.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Hash Set Lookup

Why It Works

A Set provides O(1) average-case insertion and membership testing. If any element is already in the Set when we try to add it, it must have appeared earlier in the array.

Updated Feb 2026