Push Zeros to the Back

EasyTwo Pointers

Problem

A sales sheet nums contains daily totals, where 0 marks a day with no sales. Rearrange the array in place so that all non-zero totals come first, in their original relative order, followed by all the zeros.

Do not return anything; modify nums directly using O(1) extra memory.

Example 1

Input:
nums = [0, 5, 0, 3, 8]
Output:
[5, 3, 8, 0, 0]

5, 3 and 8 keep their order; the two zeros move to the end.

Example 2

Input:
nums = [1, 2]
Output:
[1, 2]

Constraints

  • 1 ≤ nums.length ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9

Hint

Show the first hint

Think of the array as two zones: a finished prefix of non-zeros and the unprocessed rest.

Walkthrough

How to approach it

01Clarify before coding

  • Must the non-zero values keep their order? Yes, relative order is preserved.
  • Is a second array allowed? No, O(1) extra memory.
  • Do negative values count as non-zero? Yes, only exactly 0 moves.

02Brute force

Copy the non-zeros into a new list, pad it with zeros and copy it back; or repeatedly bubble each zero to the end.

Cost: The copy uses O(n) extra memory; the bubbling version is O(n²) time.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.