-6

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.

1 Answers1

0

Either take array element 0 to 4

Or change your logic inside for loop : decrease 1 inside array index eg. a[a[I] - 1] = ...like this

Sandeep Rawat
  • 214
  • 2
  • 8
  • Hi @SanDeep Rawat, i 'm begin code , please add detail solution as code for me – thang nguyen van Nov 10 '17 at 06:06
  • What actually you are trying to do in this program? – Sandeep Rawat Nov 10 '17 at 15:12
  • i try to solve this problem – thang nguyen van Nov 15 '17 at 08:56
  • 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. – thang nguyen van Nov 15 '17 at 08:57
  • Check it out, just correct the if-else part ..... .if(a[Math.abs(a[i])-1] < 0) { return Math.abs(a[i]); }else { a[Math.abs(a[i])-1] = - a[Math.abs(a[i])-1]; } – Sandeep Rawat Nov 15 '17 at 16:12