7. Move Zeroes

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.

Examples:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Input: nums = [0]
Output: [0]

Problem Breakdown:

  1. We use a slow pointer that tracks where the next non-zero element should be placed. It starts at index 0. The idea is that the slow pointer is always pointing at a position that should hold a non-zero value.
    • slowPointer = 0
  2. We iterate through the array with a fast pointer (the loop variable i). The fast pointer scans every element looking for non-zero values.
    • for i in range(len(nums)):
  3. When we find a non-zero element at the fast pointer position, we swap it with the element at the slow pointer position. This moves the non-zero to the front section of the array.
    • if nums[i] != 0:
          nums[i], nums[slowPointer] = nums[slowPointer], nums[i]
  4. After the swap, we increment the slow pointer so it points to the next position where a non-zero value should go. This ensures all non-zero values accumulate at the front in their original order.
    •     slowPointer += 1

Summary:

This is a two-pointer problem. The slow pointer marks where the next non-zero should go. The fast pointer scans the array for non-zeros. When a non-zero is found, swap it with the slow pointer position and advance the slow pointer. This naturally pushes all zeros to the end while keeping non-zeros in order.

Time and Space Complexity:

Time Complexity: O(n) - we traverse the array once.

Space Complexity: O(1) - only constant extra space is used for the pointers.

Python Solution:

def moveZeroes(nums):
    slowPointer = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[i], nums[slowPointer] = nums[slowPointer], nums[i]
            slowPointer += 1

JavaScript Solution:

var moveZeroes = function(nums) {
    let slow = 0;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] !== 0) {
            [nums[i], nums[slow]] = [nums[slow], nums[i]];
            slow++;
        }
    }
};

Java Solution:

class Solution {
    public void moveZeroes(int[] nums) {
        int slow = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                int temp = nums[i];
                nums[i] = nums[slow];
                nums[slow] = temp;
                slow++;
            }
        }
    }
}