We can do it in O(n) and constant space:
- For every element, calculate
index = Math.abs(a[i]) - 1
- Check the value at
index
- If it is positive, multiply by -1, i.e., make it negative.
- if it is negative, return (
index+1) as answer, as it means we have seen this index before.
""
static int findDup(int[] a){
for(int i=0;i