Ctrl K

Zeros to the Back

Easy
A warehouse tracks its stock as an array values, where a zero marks an empty slot. Before the report is printed, every empty slot has to move to the end of the list, while the non-zero values stay in the order they came in. Return the resulting array. The rearranging can be done right inside values, without making a copy. Try to do it in one pass with as few writes to the array as possible.
Example 1
values=[0, 7, 0, -2, 5] → [7, -2, 5, 0, 0]

The non-zero values 7, -2, 5 keep their order and move to the front, and both zeros go to the end: [7, -2, 5, 0, 0].

Example 2
values=[3, 1, 4] → [3, 1, 4]

There are no zeros, so the array stays the same.

Example 3
values=[0, 0, 9] → [9, 0, 0]

The 9 moves to the front: [9, 0, 0].

Constraints
  • 1 ≤ len(values) ≤ 10⁴
  • -2³¹ ≤ values[i] ≤ 2³¹ - 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSqueeze Repeats Out of a Sorted Array EasyDrop the Unwanted Value EasyMerge Into the Spare Tail EasyValues in Both Lists EasyShared Values With Repeats Easy
loading Python…
Input
values=[0, 7, 0, -2, 5]
Expected
[7, -2, 5, 0, 0]

Run checks the first 3 tests in your browser. Submit checks all 37 tests on the server, hidden ones included.