Please help on this code error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -3 at FindDuplicate.firstDuplicate(File.java:9) at FindDuplicate.main(File.java:19)
class FindDuplicate {
public static int firstDuplicate(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
if (a[Math.abs(a[i])] < 0)
return Math.abs(a[i]);
else
a[a[i]] = -a[a[i]];
}
return -1;
}
/* Driver program to test the above function */
public static void main(String[] args) {
int[] arr = {
2,
4,
3,
5,
1
};
System.out.println(firstDuplicate(arr));
}
}
try to solve this problem
Note: Write a solution with O(n) time complexity and O(1) additional space complexity, since this is what you would be asked to do during a real interview.
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.