Understanding Move Zeroes
Move all zeroes to the end of nums while preserving the relative order of nonzero values. Modify nums in place and return that array.
How it works
The write index is the first position not yet occupied by a retained value.
Scan left to right, write each nonzero into the next available position, then zero the remaining suffix.
Try an example
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Compact the nonzero values, then fill the remaining positions with zeroes.
Constraints
- At most 64 integers between −1,000,000 and 1,000,000.
- Preserve the order of nonzero values.
- Return the modified array for judging.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.