Editor

Move Zeros to the End

#38 · Two pointers · Beginner · 35 XP · about 6 min

Write move_zeros(nums) that rearranges the list nums in place so that every zero sits at the end, while the other numbers keep their original order. Change the list you are given rather than building a new one. The function does not need to return anything.

Examples

nums = [0, 3, 0, 5, 7]
move_zeros(nums)
nums   # now [3, 5, 7, 0, 0]

nums = [4, 0, 0, -2]
move_zeros(nums)
nums   # now [4, -2, 0, 0]

In the first example 3, 5 and 7 stay in the same order, and the two zeros move behind them.

Note

The tests look at the same list after your function has run, so returning a new list while leaving nums unchanged will not pass.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.