283. Move Zeroes

Intitution

Instead of moving non-zeros forward and filling zeros later use two pointers (i and j) place non-zero elements at the correct spot (j) also immediately sets the current i to 0 if a movement has occurred

So, it shifts non-zeros forward and backfills zeros in one go

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(n)\text{O}(n)

Code

public void moveZeroes(int[] nums) {
    for (int i = 0, j = 0; i < nums.length; ) {
        if (nums[i] != 0) {
            nums[j] = nums[i];           // Place the non-zero at index j
            if (j != i) nums[i] = 0;     // If i != j, we've moved something — set old spot to 0
            ++j;                         // Move j to the next available slot
        }
        ++i; // Always move i to check next element
    }
}

Last updated