KatInterview

Push Zeros Left While Keeping Other Values in Order

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingarraystwo-pointersin-place

Last 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.