Contains Duplicate
Master this topic with zero to advance depth.
Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Visual Representation
nums = [1, 2, 3, 1]
Using HashSet:
- 1: Not in set. Set={1}
- 2: Not in set. Set={1, 2}
- 3: Not in set. Set={1, 2, 3}
- 1: EXISTS in set! -> Return TrueExamples
Level I: Brute Force
Intuition
Compare every pair of elements. If any pair is identical, return true.
Detailed Dry Run
[1, 2, 1] (1, 2): No (1, 1): MATCH! True
Level II: Sorting
Intuition
If duplicates exist, they will be adjacent when sorted.
Detailed Dry Run
[1, 2, 3, 1] -> Sort -> [1, 1, 2, 3] nums[0] == nums[1] (1 == 1) -> True
Level III: HashSet (Optimal)
Intuition
Checking membership in a HashSet takes O(1) average time. If an element is already in the set, a duplicate is found.
Detailed Dry Run
[1, 2, 3, 1] Map {} -> {1} -> {1, 2} -> {1, 2, 3} -> Contains 1! True
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.