beginner · two pointers · read/write pointers · in place

Push the empty slots to the end

Problem

A shelf is represented as an array where 0 means an empty slot. Rearrange it in place so that all items (non-zero values) come first, in their original order, followed by all the empty slots.

Constraints

  • 0 ≤ n ≤ 32
  • values from −999 to 999
  • O(1) extra space

Examples

[0, 4, 0, 7, 2] → [4, 7, 2, 0, 0]

Show the solution

Read and write pointers with swaps

write marks the first slot after the compacted items. Every item found by read is swapped there, so items keep their order and zeros drift right.

Why it is correct

Invariant: a[0..write) holds the items seen so far in order, and a[write..read) holds only zeros. Swapping an item from read to write and advancing both keeps it; when read reaches n, all items are in front.

Complexity

Time O(n), extra space O(1). read visits each slot once; each visit does O(1) work.

Edge cases

  • No zeros: every swap is with itself.
  • All zeros: nothing moves.

Common mistakes

  • Removing zeros from a list inside a loop: O(n²) shifting.
  • Swapping with the end of the array, which breaks the items' order.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class MoveZeros
{
    /// <summary>Moves every 0 to the end in place, keeping the order of the other values. O(n), O(1) space.</summary>
    public static void Apply(int[] shelf)
    {
        int write = 0; // shelf[0..write) holds the items found so far, in order
        for (int read = 0; read < shelf.Length; read++)
        {
            if (shelf[read] != 0)
            {
                (shelf[write], shelf[read]) = (shelf[read], shelf[write]);
                write++;
            }
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/MoveZeros.cs

def apply(shelf: list[int]) -> None:
    """Move every 0 to the end in place, keeping the order of the other values. O(n), O(1) space."""
    write = 0  # shelf[:write] holds the items found so far, in order
    for read in range(len(shelf)):
        if shelf[read] != 0:
            shelf[write], shelf[read] = shelf[read], shelf[write]
            write += 1

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/move_zeros.py

package dev.bekadan.dsa.problems;
 
public final class MoveZeros {
    private MoveZeros() {
    }
 
    /** Moves every 0 to the end in place, keeping the order of the other values. O(n), O(1) space. */
    public static void apply(int[] shelf) {
        int write = 0; // shelf[0..write) holds the items found so far, in order
        for (int read = 0; read < shelf.length; read++) {
            if (shelf[read] != 0) {
                int tmp = shelf[write];
                shelf[write] = shelf[read];
                shelf[read] = tmp;
                write++;
            }
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/MoveZeros.java

#pragma once
 
#include <cstddef>
#include <span>
#include <utility>
 
namespace bekadan::dsa::problems {
 
// Moves every 0 to the end in place, keeping the order of the other values. O(n), O(1) space.
inline void move_zeros(std::span<int> shelf) {
    std::size_t write = 0;  // shelf[0, write) holds the items found so far, in order
    for (std::size_t read = 0; read < shelf.size(); ++read) {
        if (shelf[read] != 0) {
            std::swap(shelf[write], shelf[read]);
            ++write;
        }
    }
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/move_zeros.hpp