Hashing Easy
Contains Duplicate: Solution and Approach
Return true if any value appears at least twice in the array, and false if every element is distinct.
Similar questions reported in: TCS, Accenture, Capgemini, Cognizant
Example
- Input:
- nums = [1, 2, 3, 1]
- Output:
- true
Brute force first
Compare every pair: O(n²). Sorting and checking neighbours is O(n log n).
The better idea
Keep a hash set of values already seen. If the current value is already in the set, you have found a duplicate.
Steps
- Create an empty set.
- For each number: if it is in the set, return true. Otherwise add it.
- Return false after the loop.
Code
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return Falsepublic boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums) {
if (!seen.add(x)) return true; // add() returns false if x was already there
}
return false;
}Complexity
Time: O(n) on average.
Space: O(n) for the set.
Edge cases to test
- An empty array or a single element: return false.
- Negative numbers work the same way.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.