-4

import java.util.Arrays;

public class Solution {

public static int findDuplicate(int[] arr) {
    int n=arr.length;
    Arrays.sort(arr);
    for(int i=0;i<n-1;i++)
    {
        if(arr[i]==arr[i+1])
        {
           return arr[i];
        }
    }
}

}

3 Answers3

2

The problem is that you don't return anything if the logic does not enter in the "if". Consider adding a default value to return.

You can change the code like this

package com.stackoverflow.question;

import java.util.Arrays;

public class Solution {

    public static int findDuplicate(int[] arr) {
        int n = arr.length;
        Arrays.sort(arr);
        
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] == arr[i + 1]) {
                return arr[i];
            }
        }
        
        return 0; //Default value to return
    }
}
Andres Sacco
  • 650
  • 3
  • 13
1

You need to handle the case where there are no duplicates. You can either return -1, which is a convention used in places like String.indexOf, or you could throw an Exception, such as NoSuchElementException

public static int findDuplicate(int[] arr) {
    int n=arr.length;
    Arrays.sort(arr);
    for(int i=0;i<n-1;i++)
    {
        if(arr[i]==arr[i+1])
        {
           return arr[i];
        }
    }
    return -1;
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

That is because if your arr[i]==arr[i+1] never is true, the function is not going to return anything, but it has to return something, so:

public static int findDuplicate(int[] arr) {
    int n=arr.length;
    Arrays.sort(arr);
    for(int i=0;i<n-1;i++)
    {
        if(arr[i]==arr[i+1])
        {
           return arr[i];
        }
    }
    return -1;//If if the is stament is never true
}
lier wu
  • 620
  • 7
  • 23