250. Move Zeroes
You are given an integer array nums. Rearrange it so that every 0 ends up at the back of the array while all nonzero values keep their original relative order, and return the resulting array.
For instance, [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0]: the 1, 3, and 12 stay in that order, and both zeroes slide to the end.
Can you do it in one pass, shuffling values inside the array instead of building a second one?
Example 1:
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Explanation: The nonzero values 1, 3, 12 keep their order; the two zeroes are pushed behind them.
Example 2:
Input: nums = [4, 0, 1]
Output: [4, 1, 0]
Explanation: 4 and 1 stay in order and the single zero moves to the back.
Constraints:
- 1 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i] ≤ 10⁹
Hints:
If you were allowed a second array, you would copy every nonzero value into it first and pad zeroes after — that already tells you what the final layout looks like.
Keep a write pointer that marks where the next nonzero value belongs. Scan once: each time you meet a nonzero value, place it at the write pointer and advance the pointer. Everything from the pointer onward must then be zero.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [0, 1, 0, 3, 12]
Expected output: [1, 3, 12, 0, 0]