Push Zeros Left While Keeping Other Values in Order
Arrays & HashingAuto-graded · 18 test casesLast updated
Rearrange an integer list in place so all zeros come first and the non-zero values keep their original relative order, using a right-to-left two-pointer pass.
You are given a list of integers values. Rearrange it in place so that every 0 appears before every non-zero element, while the non-zero elements keep the same relative order they had in the input.
After rearranging, return the same list object. Do not build a second list of the same size to hold the result. Aim to do as few writes to the list as you reasonably can.
Details
- The number of zeros in the output equals the number of zeros in the input.
- Non-zero values, including negative ones, must appear in the output in the same left-to-right order as in the input.
- If the list has no zeros, or already has all zeros at the front, it stays unchanged.
- If the list contains only zeros, it stays unchanged.
Constraints
1 <= len(values) <= 10^4-10^4 <= values[i] <= 10^4
Examples
Example 1
Input: push_zeros_left([0, 1, 0, 3, 12])
Output: [0, 0, 1, 3, 12]
Example 2
Input: push_zeros_left([1, 7, 0, 0, 8, 0, 9])
Output: [0, 0, 0, 1, 7, 8, 9]
Hints
Hint 1
Think of the mirror problem, pushing zeros to the back. Which direction should you scan so the non-zero values end up packed against the right end?
Hint 2
Scan from right to left with a `read` index and keep a separate `write` index that starts at the last position. Each time you see a non-zero value, copy it to `write` and move `write` one step left.
Hint 3
Once the scan ends, every position from index 0 up to `write` must be zero. Fill that range with zeros. Because `write >= read` throughout, you never overwrite a value you have not read yet.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the mirror image of the well-known "move zeros to the end" task. The non-zero values must end up packed at the right end of the list in their original order, so we scan from right to left.
- Set
writeto the last index. It marks where the next non-zero value belongs. - Move
readfrom the last index down to0. Whenevervalues[read]is non-zero, copy it tovalues[write](skipping the copy ifread == write) and decrementwrite. - After the scan,
write + 1positions at the front are still unaccounted for. They are exactly the positions that must hold zeros, so set each of them to0, skipping the ones that already are.
Why it is correct
- Order is preserved. The rightmost non-zero value goes to the rightmost slot, the next one to the slot just before it, and so on. The non-zero values therefore appear in the same relative order as before.
- No unread value is overwritten.
writestarts equal toreadand only decreases when a non-zero value is found, whilereaddecreases on every step. Sowrite >= readalways holds, and writing tovalues[write]never destroys something we have yet to read. - The count of zeros is right. If
knon-zero values were placed, thenwrite = n - 1 - k, so indices0..writenumbern - k, which equals the number of zeros in the input.
Skipping the write when read == write and skipping zero-to-zero writes keeps the number of list writes low. A list with no zeros, or one that already has its zeros in front, causes no writes at all.
Edge cases
- No zeros:
read == writeat every step, nothing is written, andwriteends at-1, so the fill range is empty. - All zeros: nothing is copied,
writestays atn - 1, and every slot already holds zero. - Already arranged: the pointers stay aligned and nothing changes.
- Negative values are simply non-zero and are handled like any other.
- A single element works trivially.
Complexity
- Time: O(n), since each index is visited once per pass.
- Space: O(1) extra, because only two integer indices are used.
Reference solution
from typing import List
def push_zeros_left(values: List[int]) -> List[int]:
n = len(values)
write = n - 1 # next slot, counted from the right, for a non-zero value
# Pass 1: pack non-zero values against the right end, preserving order.
for read in range(n - 1, -1, -1):
v = values[read]
if v != 0:
if read != write:
values[write] = v
write -= 1
# Pass 2: every slot from 0 to write must be zero.
for i in range(write, -1, -1):
if values[i] != 0:
values[i] = 0
return values