Contains Duplicate
You are given an array of numbers and need to decide whether any value appears more than once.
The exact position does not matter. As soon as the same number shows up again anywhere in the array, the answer becomes true. If every value is different, the answer is false.
For example, nums = [1,2,3,1] returns true because 1 appears twice. nums = [1,2,3,4] returns false because all values are distinct.
So this problem is just asking whether the array contains at least one repeated value.
Edge cases include an empty array (false), a single element (false), and arrays with multiple duplicates. The hash set approach handles all of these without special casing.
Example Input & Output
The value 1 appears more than once.
All values are distinct.
Several values repeat, so the answer is true.
Algorithm Flow
Solution Approach
Check if an array contains any duplicate elements. Use a hash set to track numbers seen during iteration. If any number is already in the set, a duplicate exists.
Iterate through the array. For each element, check if it already exists in the hash set. If it does, return true immediately. If not, add it to the set and continue. If the loop completes without finding duplicates, return false.
Time complexity is O(n), space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public boolean solution(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int n : nums) { if (seen.contains(n)) return true; seen.add(n); }
return false;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
