Practice

Move Zeroes

Module 4 · Arrays & Dynamic Arrays

Problem

Given an integer array nums, move all 0s to the end in place while keeping the relative order of the non-zero elements.

Examples

Example 1

Inputnums = [0, 1, 0, 3, 12]Output[1, 3, 12, 0, 0]

Example 2

Inputnums = [0]Output[0]

Constraints

1 ≤ n ≤ 10⁴ · O(1) auxiliary space · minimize total writes (follow-up).

Attempt it first

Same family as the last problem — but this time nothing is discarded: the zeroes must survive, at the end. Decide what your invariant says about three regions before coding.