15% off all plans & roadmaps Use code

See plans

Move Zeroes

Updated

TL;DR: Move every 0 to the end of `nums` without changing the order of the other values, and without an extra array. Keep a write index for the next non-zero slot, then move each non-zero into that slot in one pass.

Problem

Given an integer array nums, move all 0s to the end of the array. The non-zero elements must keep their original relative order.

You must do this in place. Do not make a copy of the array.

Example 1

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

Example 2

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

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Constraints that matter

  • n up to 10^4 allows O(n^2) in theory, but the worst case does about n^2 / 2 = 5 * 10^7 moves. Aim for a single pass, which is O(n).
  • The array must change in place, so an O(n) helper array is ruled out. Two integer indices are the only extra storage you should use.
  • Values span all 32-bit integers. Compare them only with 0 and never do arithmetic on them, so overflow cannot happen.
  • The non-zero order must stay the same. That rules out swapping arbitrary pairs, such as exchanging the first zero with the last non-zero, because that breaks the order.

View on LeetCode

Hints

Hint 1

The problem asks for a stable partition.

Hint 2

A beginner finds a zero, then shifts every later element one slot left to close the gap.

Solution

Intuition

The problem asks for a stable partition. Non-zero values go first in their original order, and zeros go last.

Picture a row of seats where the front seats hold non-zero values in their original order. The write index is the first empty front seat, and each non-zero the read index finds swaps into it, sending a zero back.

This is an in-place array modification problem, which falls under the Two Pointers pattern. One pointer reads every element. The other marks the first slot that does not yet hold a finished non-zero value.

The write pointer only advances past non-zero values, so everything before it is the non-zero prefix, in order. The read pointer never moves backwards, so each element is examined once. Zeros are never copied forward. They are left behind, and they end up in the tail.

Sorting by a zero flag also solves the problem if the sort is stable. That costs O(n log n) and needs a custom comparator. A single pass does the same job with less work, so the pointer method is the one to learn.

Watch the pattern animation

Worked example

Input: nums = [4, 2, 0, 1, 0, 0, 5]
Output: [4, 2, 1, 5, 0, 0, 0]
Explanation: The three zeros at indices 2, 4 and 5 end up at the back. The non-zero values 4, 2, 1 and 5 keep their original order.

Approach 1: Brute force: shift zeros to the end

A beginner finds a zero, then shifts every later element one slot left to close the gap. The zero goes to the back of the array. The scan repeats until no zero remains in front of the zero tail. Each shift touches up to n elements, and there can be up to n zeros to remove, so the work adds up quickly.

The variable end marks where the zero tail starts. Everything from end onward is already finished, so the scan never looks there.

Steps

  1. Set end to the array length. Indices from end onward hold finished zeros.
  2. Set i to 0.
  3. While i is less than end, look at nums[i].
  4. If nums[i] is not zero, increment i.
  5. If nums[i] is zero, shift nums[i+1] through nums[end-1] one slot left.
  6. Write 0 into nums[end-1] and decrement end.
  7. Do not increment i after a shift. A new value now sits at i and must be checked.

Dry run

Start with end = 7, i = 0, nums = [4, 2, 0, 1, 0, 0, 5].

  • i = 0 and i = 1 hold 4 and 2, which are non-zero. Move i to 2.
  • i = 2 holds 0. Shift indices 2 to 5 left, which gives [4, 2, 1, 0, 0, 5, 5]. Write 0 at index 6, so nums = [4, 2, 1, 0, 0, 5, 0]. Set end = 6.
  • i = 2 holds 1. Move i to 3.
  • i = 3 holds 0. Shift indices 3 to 4 left, then write 0 at index 5. nums = [4, 2, 1, 0, 5, 0, 0]. Set end = 5.
  • i = 3 holds 0 again. Shift index 4 into index 3, then write 0 at index 4. nums = [4, 2, 1, 5, 0, 0, 0]. Set end = 4.
  • i = 3 holds 5, so move i to 4. Now i equals end, and the loop stops.

The result is [4, 2, 1, 5, 0, 0, 0], which matches the expected output.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the array length. Each shift moves at most n - 1 values, and each zero removal costs one shift. The end index starts at n and only falls, so there are at most n removals. The worst case, such as n - 1 zeros followed by one non-zero, does about n^2 / 2 moves.

PythonTested in our runner

from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        end = len(nums)  # nums[end:] already holds zeros
        i = 0
        while i < end:
            if nums[i] == 0:
                for j in range(i, end - 1):
                    nums[j] = nums[j + 1]
                nums[end - 1] = 0
                end -= 1
            else:
                i += 1

Approach 2: Two pointers: compact, then fill zeros

What's slow in the brute force is the repeated shifting. Each zero forces every later value to move, and the same non-zero values move again and again. Each non-zero only needs one write, to its final slot.

The insight that fixes it: copy each non-zero forward to the next free slot, in order. Once the scan ends, every slot from the write index onward gets a 0. This does one write per non-zero plus one write per tail slot.

Steps

  1. Set write to 0.
  2. Scan read from 0 to n - 1.
  3. When nums[read] is not zero, copy it into nums[write].
  4. Increment write after each copy.
  5. After the scan, set every index from write to n - 1 to 0.

Dry run

Start with write = 0 and nums = [4, 2, 0, 1, 0, 0, 5].

  • read = 0 holds 4. Copy it to index 0. write = 1.
  • read = 1 holds 2. Copy it to index 1. write = 2.
  • read = 2 holds 0. Skip it.
  • read = 3 holds 1. Copy it to index 2. write = 3.
  • read = 4 and read = 5 hold zeros. Skip them.
  • read = 6 holds 5. Copy it to index 3. write = 4.

The array is now [4, 2, 1, 5, 5, 0, 5]. Indices 4, 5 and 6 are filled with 0, which gives [4, 2, 1, 5, 0, 0, 0]. This matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the array length. The first loop visits each index once and does at most one copy per step. The fill loop writes at most n slots, one per index. Both loops are linear, so the total time is O(n). Only write and the loop indices are stored, so the space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        write = 0
        for x in nums:
            if x != 0:
                nums[write] = x  # write never passes the value being read
                write += 1
        for i in range(write, len(nums)):
            nums[i] = 0

The In-place Array Modification infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 3: Guarded swap, one passOptimalIn-place Array Modification

What's slow in compact then fill is the second pass. It writes zeros over the whole tail, including slots that already held zeros. Swapping does the same job in one pass, and it keeps the order too.

The invariant is the key. Everything before write is the non-zero prefix in order. Everything from write to read - 1 is zero.

So when read finds a non-zero, swapping it with nums[write] moves that zero to read. The zeros drift right as the scan goes. When the two indices match, the swap does nothing, so the guard skips it.

Why it is correct. Every non-zero is either swapped into the write slot or already sits there. The slots from write to read minus one always hold zeros, so a swap only moves a zero forward. Non-zeros keep their relative order because write never passes a non-zero it has not yet placed.

Steps

  1. Set write to 0.
  2. Scan read from 0 to n - 1.
  3. If nums[read] is zero, continue to the next index.
  4. If write differs from read, swap nums[write] and nums[read].
  5. Increment write.

Dry run

Start with write = 0 and nums = [4, 2, 0, 1, 0, 0, 5]. Each row shows the state after that read step.

readnums[read]write beforeactionnums after
040same index, no swap, write = 1[4, 2, 0, 1, 0, 0, 5]
121same index, no swap, write = 2[4, 2, 0, 1, 0, 0, 5]
202zero, skip[4, 2, 0, 1, 0, 0, 5]
312swap indices 2 and 3, write = 3[4, 2, 1, 0, 0, 0, 5]
403zero, skip[4, 2, 1, 0, 0, 0, 5]
503zero, skip[4, 2, 1, 0, 0, 0, 5]
653swap indices 3 and 6, write = 4[4, 2, 1, 5, 0, 0, 0]

The final row gives [4, 2, 1, 5, 0, 0, 0], which matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the array length. The loop runs n times. Each iteration does at most one swap, which costs a fixed number of reads and writes. The total is at most about 3n operations, so the time is O(n). Only read and write are stored, so the space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        write = 0
        for read in range(len(nums)):
            if nums[read] != 0:
                # Skip the swap when both indices already match.
                if write != read:
                    nums[write], nums[read] = nums[read], nums[write]
                write += 1

Common mistakes

  • Testing nums[write] != 0 instead of nums[read] != 0. The check looks at the slot being filled, so real non-zeros get skipped. Test the value that the read pointer found.
  • Copying non-zeros forward without a zero fill afterwards. The tail keeps stale copies of values that already moved. Set every index from write to the end to 0.
  • Writing write++ on every iteration, including zeros. The non-zero prefix then gets zeros in the middle. Increment write only after a non-zero is placed.
  • Using i++ right after a shift in the brute force. The value that slid into i is never checked, so a zero there survives. Keep i in place after each shift.
  • Returning a new list, or writing nums = result in Python. That only rebinds the local name, and the caller's list stays unchanged. Write by index, or use nums[:] = result.

Edge cases

  • [0] returns [0]. A single element needs no shifting, and the fill pass writes the same zero back.
  • [1] or [-5] returns the input unchanged. With no zeros, write ends at n and the fill loop does nothing.
  • [0, 0, 0] returns [0, 0, 0]. The write index never moves, and the fill pass writes zeros over the whole array.
  • [1, 2, 0, 0] returns [1, 2, 0, 0]. Zeros already at the end keep their place, and the non-zero order holds.
  • [-2147483648, 0, 2147483647] returns [-2147483648, 2147483647, 0]. The code compares values only with 0, so extreme magnitudes are safe.

Follow-ups interviewers ask

Could you minimize the total number of operations?
Count writes first. Compact then fill writes each non-zero once, plus one write per tail slot. The guarded swap writes two slots for each non-zero that moves. Both are O(n). The guard in the swap avoids self-swaps. You can add the same guard to the compact version by skipping copies where write equals read. Name what you count, because the two versions differ in writes.
What if the value to move is not zero, for example every 7?
Change the test from != 0 to != target. The compact version fills the tail with target instead of 0. The guarded swap works unchanged, because its invariant only depends on the test and not on the value 0.
What if nums is a singly linked list?
Walk the list once with a read node. Relink each non-zero node after the last non-zero node, and collect the zero nodes into a separate chain. Attach the zero chain at the end. The time is O(n), and the extra space is O(1), because you move pointers and do not copy nodes.

Move Zeroes FAQ

What is the time complexity of Move Zeroes?

The optimal solutions run in O(n) time, where n is the array length, because each index is read a constant number of times. The brute force that shifts elements left runs in O(n^2) in the worst case.

Why use two pointers for Move Zeroes?

Two pointers let one index scan the array while the other marks where the next non-zero belongs. The write index never passes the read index, so the non-zero order holds and no value is handled more than a fixed number of times.

Can Move Zeroes be solved in O(1) extra space?

Yes. The compact-then-fill version and the guarded swap both use only two integer indices. The version that needs O(n) extra space copies the non-zeros into a new array, which the problem forbids.

Why does my Python solution not change the input?

Assigning nums = result only rebinds the parameter name inside the method. Write into the list by index, or use slice assignment nums[:] = result, so the caller sees the change.

Asked at

See which companies ask this — Pro

Practise it