Community Problem

Move Zeroes

Difficulty: Easy

Move every zero to the end of the array in place while keeping the relative order of the non-zero elements.

Move Zeroes

Move every zero to the end of the array in place while keeping the relative order of the non-zero elements.

EASY
Free
arrays
two-pointers
fundamentals
rajtanaka

By @rajtanaka

February 7, 2026

·

Updated May 18, 2026

505 views

7

4.2 (10)

I see this one in the first 15 minutes of a screen more than almost any other Easy, usually right after a candidate gets through Two Sum. The reason is the relative-order constraint: it rules out the swap-from-the-ends shortcut and forces the cleaner write-pointer pattern that scales to the harder "compact in place" family (Remove Element, Remove Duplicates from Sorted Array, etc.).

Move Zeroes

Given an integer array nums, move all 0s to the end of the array while keeping the relative order of the non-zero elements unchanged. You must do this in place without allocating a new array. The function does not need to return anything; modify nums directly.

Examples

Example 1:

  • Input: nums = [0, 1, 0, 3, 12]
  • Output: nums becomes [1, 3, 12, 0, 0]
  • Explanation: Non-zero values 1, 3, 12 keep their original relative order; the two zeros land at the end.

Example 2:

  • Input: nums = [0]
  • Output: nums becomes [0]
  • Explanation: Single-element zero array is unchanged.

Example 3:

  • Input: nums = [1, 2, 3]
  • Output: nums becomes [1, 2, 3]
  • Explanation: No zeros, no rearrangement.

Example 4:

  • Input: nums = [0, 0, 1]
  • Output: nums becomes [1, 0, 0]
  • Explanation: Two leading zeros migrate to the back; the lone non-zero shifts forward.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Follow-up

Can you minimize the number of writes? The two-pointer scan with swaps does O(n) writes; the simpler "compact then pad" version does up to 2 * (count of non-zeros) writes, which is fewer when the array is mostly zeros.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems