If all elements are in the range 1 to n (or 0 to n-1), we can use the array itself to track seen elements by negating the value at the index corresponding to each element.
classSolution {
public:bool hasDuplicates(vector<int>& arr) {
for (int i =0; i < arr.size(); ++i) {
int idx = abs(arr[i]);
if (arr[idx] <0) return true;
arr[idx] =-arr[idx];
}
return false;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicbooleanhasDuplicates(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int idx = Math.abs(arr[i]);
if (arr[idx]< 0) returntrue;
arr[idx]=-arr[idx];
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
classSolution:
defhas_duplicates(self, arr: list[int]) -> bool:
for i in range(len(arr)):
idx = abs(arr[i])
if arr[idx] <0:
returnTrue arr[idx] =-arr[idx]
returnFalse