I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview
Here is a solution in O(N) time and O(1) extra space for finding duplicates :-
public static boolean check_range(int arr[],int n,int m) {
for(int i=0;i=m)
return(false);
}
System.out.println("In range");
int j=0;
while(j
Explanation:-
- Bring number to range (0,m-1) by arr[i] = arr[i] - n if out of range return false.
- for each i check if arr[arr[i]] is unoccupied that is it has value less than m
- if so swap(arr[i],arr[arr[i]]) and arr[arr[i]] = arr[arr[i]] + m to signal that it is occupied
- if arr[j] = j and simply add m and increment j
- if arr[arr[j]] >=m means it is occupied hence current value is duplicate hence return false.
- if arr[j] >= m then skip