Move Zeroes
A shelf is a row of slots. nums[i] is the item in slot i, and 0 means the slot is empty. Slide every item toward the front so that all the empty slots end up at the back, and keep the items in the order they started in. Return the rearranged shelf. Limits: 1 <= nums.length <= 500000, -1000000000 <= nums[i] <= 1000000000. Items can be negative; only 0 means empty. Think about: how many times does each item really have to move? Example (shelf 0, 5, 0, 0, 8, 3): items in order: 5, 8, 3 empty slots: 3 answer: [5, 8, 3, 0, 0, 0]
You have a row of slots where 0 means empty, and you want every item slid toward the front without changing the order the items came in. It's a good warm-up because the same in-place move shows up in a whole family of array problems. The classic trap is shifting everything over each time you meet an empty slot, which feels fine on ten items and crawls on half a million. Expect up to 500,000 slots, with values from -1,000,000,000 to 1,000,000,000.
Examples
You write
move_zeroes(nums: List[int])
Example 1
- Input
- nums = [0,5,0,0,8,3]
- returns
- [5,8,3,0,0,0]
Example 2
- Input
- nums = [0]
- returns
- [0]
Save this for your laptop
The editor and Run need a bigger screen. The link opens Move Zeroes ready to code. It is free, and the editor needs no account.
The pattern behind it
Two Pointers
I reach for it when
- The array is sorted, or you can sort it.
- You need a pair, a triple or a palindrome.
Say this before you type. Say what each pointer means and what a move to the left or right rules out.
All 26 Two Pointers problemsArrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 126 Arrays & Hashing problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.