InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Move Zeroes

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug