Pattern visualizer
Contains Duplicate
Sorting would work but costs O(n log n). A hash set answers 'have I seen this value?' in O(1), so one left-to-right pass suffices: check each value against the set BEFORE adding it — the instant a lookup hits, a repeat exists and we can stop early. Animated on: Given an integer array, return true if any value appears at least twice, otherwise false..
Hash-set membership scan
time O(n)space O(n)step 1 / 9
7
[0]12
[1]4
[2]19
[3]15
[4]23
[5]4
[6]11
[7]line 2
Seed an empty set 'seen'. Walk i left to right asking one question per cell: is this value already in the set? A hit means a duplicate.
Pseudocode
1FUNCTION containsDuplicate(nums):2 make an empty set of seen values3 FOR i from 0 to (length of nums) - 1:4 IF nums[i] is already in the set: RETURN true5 add nums[i] to the set6 RETURN false
← / → step · space play · Home restart