Move Zeroes – Solution & Complexity

Quick practice for Move Zeroes: 3 reasoning beats, no typing

Solution Walkthrough

  1. Step 1: Understand the Goal

    • Move every 0 to the end of the array.
    • Preserve the relative order of all non-zero values.
    • The function returns the resulting array.
  2. Step 2: Simple Extra-Array Approach

    • Collect all non-zero values first.
    • Count how many zeroes are needed at the end.
    • This is easy to understand but uses extra space.
    def move_zeroes(nums):
        non_zeroes = [num for num in nums if num != 0]
        zero_count = len(nums) - len(non_zeroes)
        return non_zeroes + [0] * zero_count
  3. Step 3: Use a Write Pointer

    • Keep a pointer for where the next non-zero value should be placed.
    • Scan the array from left to right.
    • Every non-zero value is written to the next available position, preserving order.
  4. Step 4: Fill the Remaining Positions with Zeroes

    • After all non-zero values are written, everything from the write pointer to the end should be 0.
    • This produces the same array shape without needing a second array.
    • Finally, return nums.
    def move_zeroes(nums):
        write = 0
        for num in nums:
            if num != 0:
                nums[write] = num
                write += 1
        for i in range(write, len(nums)):
            nums[i] = 0
        return nums
  5. Step 5: Final Solution and Complexity

    • The solution keeps non-zero elements in their original relative order.
    • Time complexity is O(n).
    • Space complexity is O(1) besides the input array.
    def move_zeroes(nums: list[int]) -> list[int]:
        write = 0
        for num in nums:
            if num != 0:
                nums[write] = num
                write += 1
        for i in range(write, len(nums)):
            nums[i] = 0
        return nums

FAQ