InterviewPrepKit

Home / Coding / Two Pointers

Move Zeroes

easy Original ↗
Solving tips
  • Only nonzeros have destinations: use a slow write pointer and a fast scan pointer, this is a stable in-place partition on 'is nonzero'.
  • One-pass swap: when fast finds a nonzero, swap it into nums[slow] and advance slow; the region between the pointers is always zeros.
  • Move nonzeros forward, never move/delete zeros (list.remove in a loop is O(n^2) and skips elements); preserve relative order by writing left-to-right.
  • O(n) time, O(1) space; guard with `if slow != fast` to skip self-swaps and minimize writes for the follow-up.

Problem

Given an integer array nums, push every 0 to the back of the array while keeping all the nonzero elements in their original relative order. Do it in place — mutate nums rather than returning a new array.

Follow-up: minimize the total number of operations (writes/swaps).

Examples

  • nums = [0,1,0,3,12][1,3,12,0,0] The nonzeros 1,3,12 keep their order; the two zeros slide to the end.
  • nums = [0][0] A single zero stays put — there is nothing to reorder.
  • nums = [2,1][2,1] No zeros at all; the array is untouched.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • Must be in place (O(1) extra space expected); a single O(n) pass is achievable.

Think about it first

Hint 1 "Zeros at the end, nonzeros in order" means the final array is just the nonzero subsequence followed by padding. Could you compute where each nonzero *belongs*?
Hint 2 Keep a slow pointer marking the next slot to fill with a nonzero value, and a fast pointer scanning the array. What invariant does the slow pointer maintain?
Hint 3 Invariant: everything left of the slow pointer is the nonzeros seen so far, in order. When the fast pointer hits a nonzero, swap it into the slow slot and advance slow. After the scan, all zeros have been swapped behind the slow pointer automatically.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.