TRT
Sign in
easyFoundationsLeetCode#read and write indexes#compaction

Move zeroes

Move every 0 in an array to the end while keeping the other elements in order, in place and in one pass.

The Runtime Theory Team1 min read
Taught inInserting and deleting in the middleAn array has no gaps, so inserting or deleting anywhere but the end shifts everything after that point. Knowing that cost, and the tricks that avoid it, decides how you use arrays.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [0, 1, 0, 3, 12]

out[1, 3, 12, 0, 0]

innums = [0]

out[0]

innums = [1, 2, 3]

out[1, 2, 3]

Given an array of integers, move all 0s to the end while keeping the relative order of the non-zero elements. Do it in place.

Before you code

Removing each zero and appending it at the end shifts the rest of the array every time: O(n²). Instead, think of it as compacting the non-zero elements to the front and filling what is left with zeros.

Hints

  1. Keep a write index that starts at 0. Walk the array with a read index.
  2. Each time the read index finds a non-zero, copy it to the write index and advance the write index.
  3. After the pass, fill every slot from the write index to the end with 0.
  4. Variant: swap nums[read] with nums[write] instead of copying, and the zeros end up at the back without a second loop.

Production & complexity notes

When solving Move zeroes on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Inserting and deleting in the middle to reinforce the underlying pattern.

What it practices

Removing many elements in one pass instead of one shift at a time, from Inserting and deleting in the middle.

Not started

Sign in to save your learning progress.

Sign in to save