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.
This problem like most other problems has multiple solutions.
The easiest way to detect non-unique values is by using the bruteforce approach, we take the first element of the array and compare it to the other elements, and we will repeat thesame process for all the elements in the array. this approach will give us a time complexity of O(n^2) and space of O(1) since we do not need extra space for this. This is not a bad solution, the question can we do better?
We can use a HashSet, you might ask why a HashSet, a HashSet will not allow duplicate values.
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> uniqueValues = new HashSet<>();
for(int i=0; i<nums.length; i++){
if(uniqueValues.contains(nums[i])){
return true;
}
uniques.add(nums[i]);
}
return false;
}
}
Time: O(n) Space: O(n)
You can comment with solutions for different languages