Circular Sorting

Prashant Mishra - Mar 3 - - Dev Community

Find missing number

class Solution {
    public int missingNumber(int[] nums) {
        //circular sorting works by putting numbers at their respective index
        //then finally finding out which number is not at its index that number will 
        //be missing
        int i =0;
        while(i < nums.length){
            int j = nums[i]-1; //nums[i] should be put at index nums[i]-1;
            if(j<0){i++; continue;}
            else if(j!=nums[j]-1) {
                //if the number is not at its correct index then put it on its correct index
                //swap numbers at index i and j
                int temp  = nums[j];
                nums[j] = nums[i]; //note j = nums[i]-1; //correct index for number nums[i]
                nums[i] = temp;
            }
            else i++;
        }
        for(i=0;i<nums.length;i++){
            if(i!=nums[i]-1) return i+1;//missing number
        }
        return 0; //if the 0 is missing
    }
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .