You get an integer array nums. Push every 0 to the back of the array, and keep the other values in the same order they had before.
Change nums itself; do not build and return a second array. The function returns nothing.
Example 1
Input: nums = [0, 4, 0, 0, 7, 2] Output: [4, 7, 2, 0, 0, 0] Why: 4, 7, 2 keep their order; three zeros go last
2 more examples and the constraints
Example 2
Input: nums = [0] Output: [0] Why: a lone zero has nowhere to move
Example 3
Input: nums = [3, 1, 2] Output: [3, 1, 2] Why: no zeros, so nothing changes
Constraints
- 1 ≤ nums.length ≤ 10,000
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- Follow-up: keep the number of writes small
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Pack, then fill with zerosO(n)
- Swap into the write slotO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Writes for 10,000 items | Verdict |
|---|---|---|---|
| Pack, then fill with zeros | O(n) | Passes; two passes | |
| Swap into the write slot | O(n) | Best; one pass |
n = length of nums. Both are linear; the swap version needs no second loop.
Edge cases to test
- No zeros. [3, 1, 2]: every swap is with itself and the array is unchanged.
- Only zeros. [0, 0, 0, 0]:
writenever moves and nothing is swapped. - Zeros at the front. [0, 0, 0, 8]: the 8 is swapped all the way to slot 0 in a single swap.
- Negative and extreme values. Only 0 is special. Values such as −2³¹ are non-zero and keep their place in the order.
Common mistakes
- Swapping zeros forward instead of non-zeros, which scrambles the order of the other values.
- Removing zeros with a delete inside the loop, which shifts the array and costs O(n²).
- Building a new array and returning it, when the caller only looks at
nums.
How to talk through it
- 1Clarify. In place? Must the non-zeros keep their order? Can values be negative?
- 2Give the two-pass idea. Pack the non-zeros forward with a write index, then fill the tail with zeros. O(n), O(1) space.
- 3Merge the passes. Swap instead of copy: the zero that was at
writelands where the value came from, so no fill loop is needed. - 4State the invariant. Before
write: placed non-zeros. Fromwritetoi: zeros. That is why the order is kept. - 5Test out loud. Run no zeros, only zeros and zeros at the front before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?