Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Move Zeroes

easytwo-pointersin-place

Problem

Given an integer array nums, rearrange it in place so that every 0 is moved to the end while all non-zero elements keep their original relative order. Do not allocate another array; the function returns nothing and modifies nums directly.

  • nums has between 1 and 30,000 elements.
  • Elements are arbitrary integers, positive or negative; only exact zeros move.

Examples

  • nums = [4, 0, 0, 9, 0, 2] → [4, 9, 2, 0, 0, 0]. The non-zeros 4, 9, 2 keep their order.
  • nums = [0, 0] → [0, 0]. Nothing to move.
  • nums = [5, 8] → [5, 8]. No zeros; the array must be left untouched.

Hints

  1. If you were allowed a second array, what would you copy into it and in what order? Can the input array itself serve as that destination?
  2. Keep an index that marks where the next non-zero belongs; everything before it is already in final position.
  3. Read/write two pointers: scan with read, and whenever nums[read] is non-zero, swap it into nums[write] and advance write.

Last reviewed 8 September 2026