← All problems

10. Move Zeroes

EasyTwo PointersOriginal on LeetCode ↗

Move every 0 in nums to the end of the list while keeping the other numbers in their original order.

Change nums in place and don't return anything; the list itself is checked after your function finishes. Try not to make a copy of the list.

Constraints

  • 1 <= len(nums) <= 10000
  • -2^31 <= nums[i] <= 2^31 - 1

Examples

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

Hints

Hint 1

Keep a write position for the next non-zero value.

Hint 2

Copy non-zeros forward, then fill the rest with zeros (or swap as you go).

Hint 3

Swapping a non-zero into the write position (instead of copying, then zero-filling) does it in one pass.

Python 3

Run checks the examples · Submit checks every test. The first run downloads Python (about 10 MB) and takes a few seconds.