Move Zeroes

Easy

Topics
ArrayTwo Pointers

Given an integer array nums, move all 0's to the end while keeping the relative order of the non-zero elements. Return the resulting array.

Example 1

before010312
after131200
Zeros move to the end and everything else keeps its relative order, which rules out swapping with the end. A write pointer that only advances on a non-zero does it in place: copy forward, then fill the tail with zeros.
Shaded cells are the zeros, before and after.
Input:  nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2

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

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Keep a "write" pointer marking where the next non-zero value belongs. Sliding every non-zero value forward compacts them in order, and the zeros are pushed to the tail for free.

Approach

  1. Let j = 0 be the slot for the next non-zero.
  2. Scan with i; when nums[i] != 0, swap it into position j and advance j.
  3. After the pass, [0, j) holds the non-zeros in order; the rest are zeros.

Walkthrough

nums = [0, 1, 0, 3]
i=0 (0) skip           j=0
i=1 (1) swap -> [1,0,0,3] j=1
i=2 (0) skip           j=1
i=3 (3) swap -> [1,3,0,0] j=2

Complexity

  • Time — O(n): single pass.
  • Space — O(1): in place with one index.

Common Pitfalls

  • Swap, do not assign. Writing nums[j] = nums[i] copies the value forward without clearing where it came from, so [0,1,0,3,12] ends up 1 3 12 3 12 instead of 1 3 12 0 0 -- the zeros are never written and the tail is duplicated.
  • Relative order of the non-zero values has to survive, which rules out the two-pointer-from-both-ends trick that works for plain partitioning.

Full Solution — all languages

class Solution:
    def moveZeroes(self, nums):
        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[j], nums[i] = nums[i], nums[j]
                j += 1
        return nums
SensAI
Beta
Tap the mic to stop voice mode