Problem 249321 · easy · Phase 02 Linear Data Structures

Move Zeroes

lists · in-place · two pointers

Because a list lives in one block of memory, you can rearrange it in place without allocating a second list. Many interview problems insist on this to save memory.

Given a list of integers nums, move every 0 to the end while keeping the relative order of the non-zero elements. You must change nums itself and return nothing: the tests look at the list after your function runs, so building and returning a new list will not pass.

Examples

Input:  nums = [0, 1, 0, 3, 12]
After:  nums = [1, 3, 12, 0, 0]
Input:  nums = [0]
After:  nums = [0]

Constraints

  • 0 <= len(nums) <= 1000
  • Do not create a copy of the list; work inside nums.

Goals

  • Modify a list in place instead of building a new one
  • Use a read index and a write index that move at different speeds
Starting Python…