01
02
03
04
05
06
07
08
09
10
11
A
A2Z Sheet

68. Move Zeros to End & The Snowplow

Easy
Step 3: Solve Problems on Arrays [Easy -> Medium -> Hard]›Easy

Move Zeros to End & The Snowplow

EasyFunction: moveZerosToEnd()
ASCI Mission Breakdown • Simple as Hell
"Push all zeros to the end of the array while keeping non-zeros in their original relative order."
Real-World Metaphor:

Imagine a subway car. Seated passengers stay in the same order, while empty seats are slid all the way to the back door so new passengers can board.

Interactive Visual WalkthroughARRAY-POINTERS
Step 1 / 3
Array: [0, 1, 0, 3, 12]
insertPos
0
[0]
1
[1]
0
[2]
3
[3]
12
[4]
Memory Notepad / State Tracker
insertPos:0
Evaluating

1. Encounter Zero at Index 0

insertPos stays at index 0. Scanner i searches ahead for the first non-zero.

How to Think About This (Mental Model)

  1. Maintain an insertPos pointer starting at index 0.
  2. Loop through the array: whenever nums[i] !== 0, put it at nums[insertPos] and increment insertPos.
  3. Once all non-zeros are placed, fill the rest from insertPos to nums.length with 0s.

### The Mission Imagine a row of seats in a theatre: some seats have people sitting in them (numbers `> 0`), and some seats are completely empty (represented by `0`). Your mission is to act as a **snowplow**: slide every single seated person forward toward the front row so they stay in their exact original order, while pushing all the empty seats (`0`s) to the very back.

Examples

Example 1
Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Topic Tags:
Solve Problems on Arrays [Easy -> Medium -> Hard]EasymoveZerosToEnd
14px
Ln 1:Col 1
8 lines•118 chars
Spaces: 2•UTF-8
JS(Node v20.12)