Problem 249321 · easy · Level 02 Linear Data Structures

Gaps to the End of the Log

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.

A sensor log nums writes 0 whenever a reading is missing; every other value, negative ones included, is a real reading. Before the log is plotted, the gaps are gathered at the back: the real readings move to the front, still in the order they were taken, and all the 0s follow them. Rearrange 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. Each test calls after_move(nums), which runs your function and returns nums as it is afterwards.

Examples

Input:  nums = [0, 4, 0, 0, 9, 2]
After:  nums = [4, 9, 2, 0, 0, 0]
Input:  nums = [0, 0, 0]
After:  nums = [0, 0, 0]
Explanation: a log with no readings at all stays as it is.
Input:  nums = [3, 0, -1, 0, 2]
After:  nums = [3, -1, 2, 0, 0]
Explanation: the non-zero values keep their original order (they are not sorted), and -1 is non-zero.

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…