Java: Accepted Solution. Array manipulation

  • 0

    Logic: The array contains number from 0-n and has one number missing, hence the size of the array is n.
    Consider the numbers within the array as the array indexes. For each number within the range, negate the number in the index corresponding to the number.
    If the number to be negated is 0, replace it with a negative number outside of the range of the array.
    Look through the array to find the positive numbers, the index will correspond to the missng value.

    public class Solution {
    public int missingNumber(int[] nums) {

        for(int i = 0; i < nums.length; i++) {
            if(Math.abs(nums[i]) < nums.length){
                nums[Math.abs(nums[i])] = - nums[Math.abs(nums[i])];
                if(nums[Math.abs(nums[i])] == 0)
                    nums[Math.abs(nums[i])] = -(nums.length + 2);
            else if(Math.abs(nums[i]) == nums.length + 2)
                nums[0] = -nums[0];
        for(int i = 0; i < nums.length; i++){
            if(nums[i] >= 0)
                return i;
        return nums.length;


Log in to reply

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