Magicsheet logo

Move Zeroes

Easy
55.9%
Updated 6/1/2025

Move Zeroes

What is this problem about?

The Move Zeroes problem asks you to move all zeroes in an integer array to the end while maintaining the relative order of all non-zero elements — in place, without using extra space. This Move Zeroes coding problem is one of the most widely asked easy two-pointer problems in technical interviews.

Why is this asked in interviews?

Nearly every major company — Apple, Cisco, Google, Amazon, Meta, Microsoft, Goldman Sachs, and dozens more — asks this problem. It tests the two-pointer technique, in-place array modification, and order preservation simultaneously. The array and two pointers interview pattern is the foundational skill here. Interviewers also use it to assess code clarity under pressure.

Algorithmic pattern used

Two-pointer (slow-fast). Maintain a writePos pointer starting at 0. Scan the array with a readPos pointer. For every non-zero element at readPos, place it at writePos and advance writePos. After the scan, fill all positions from writePos to the end with 0. This ensures all non-zeros come first in original order, followed by all zeros.

Example explanation

Array: [0, 1, 0, 3, 12]. writePos = 0.

  • readPos 0: 0 (skip).
  • readPos 1: 1 → arr[0]=1, writePos=1.
  • readPos 2: 0 (skip).
  • readPos 3: 3 → arr[1]=3, writePos=2.
  • readPos 4: 12 → arr[2]=12, writePos=3. Fill arr[3..4] with 0. Result: [1, 3, 12, 0, 0].

Common mistakes candidates make

  • Using a temporary array (violates in-place requirement).
  • Swapping zeros with non-zeros (works but potentially slower: O(number of zeros * n)).
  • Not preserving the relative order of non-zero elements.
  • Filling from writePos to end with 0 but getting the range wrong.

Interview preparation tip

Move Zeroes is the canonical two-pointer array partition problem. The pattern — one pointer to read, one to write — applies to dozens of related problems: move all even numbers to front, segregate negative and positive, partition by pivot. Memorize this pattern and practice adapting it to different conditions (non-zero, positive, greater-than-k, etc.). Clean code on this problem signals strong two-pointer fundamentals to any interviewer.

Similar Questions