Easiest java solution with explanation

  • 2

    Here is the algorithm:
    First sort the input.
    Then check whether element at position i and i + 1 are the same or not.
    If the two elements are the same , then add one to the loop counter , if they are not the same then element at position i is the missing one return it.
    What happens if the missing element is at position nums.length-1 e.g. [1,1,2,2,3,3,4,4,5] ?
    to handle this case we need to a boolean variable to check if the length is odd or not.
    if it's odd then set the boolean variable to true.
    After the loop finished and it didn't return any value then element at the last position is the solution.

    public int singleNumber(int[] nums) {
        boolean b = false;
        if(nums.length % 2 != 0 ) b = true;
        for(int i = 0; i < nums.length-1; i++ ){
             if(nums[i] != nums[i+1]){
                 return nums[i];
           return nums[nums.length-1];
        return 0;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.