Example 1
- Input
- nums = [1, 2, 3, 1]
- Output
- true
The value 1 appears at indices 0 and 3, so a duplicate exists.
Given an integer array, decide whether any value appears at least twice. Return true when a repeat exists and false when every element is distinct.
Given an integer array nums, return true when two different indices contain the same value. Return false when all values are distinct.
Only the existence of a repeat matters: you do not need its index, its frequency, or a modified array.
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9The value 1 appears at indices 0 and 3, so a duplicate exists.
Every element appears exactly once, so there is no duplicate.
Several values repeat, for example 1 appears three times.
Imagine checking names at a door: each new arrival is compared with the names already checked in. In [1, 2, 3, 1], the first three values are new, but the final 1 is already on the list. A set stores distinct values and answers whether a value is present; it remembers the past without comparing every pair again.
Reveal Brute Force: intuition, complexity, and code
[7], returns false; two different indices are required. Empty arrays are outside the public constraints.[2, 2, 2], returns true at the second value in the hash-set approach.[1, 2, 3, 1], exercises checking the last element; [1, 2, 3, 4] requires scanning to the end.[-1, 0, -1] returns true.[-1000000000, 1000000000] are distinct. A Boolean array indexed by value would waste memory across this large range.j = i compares each element with itself and incorrectly returns true.For Arrays & Hashing questions about whether a value appeared earlier, a hash set turns repeated searches of the past into one expected linear scan. Keep a map instead when you also need counts or an earlier index.