Move Zeroes – Solution & Complexity
1. Understand the Goal
- Move every
0to the end of the array. - Preserve the relative order of all non-zero values.
- The function returns the resulting array.
2. Simple Extra-Array Approach
- Collect all non-zero values first.
- Count how many zeroes are needed at the end.
- This is easy to understand but uses extra space.
3. Use a Write Pointer
- Keep a pointer for where the next non-zero value should be placed.
- Scan the array from left to right.
- Every non-zero value is written to the next available position, preserving order.
4. Fill the Remaining Positions with Zeroes
- After all non-zero values are written, everything from the write pointer to the end should be
0. - This produces the same array shape without needing a second array.
- Finally, return
nums.
5. Final Solution and Complexity
- The solution keeps non-zero elements in their original relative order.
- Time complexity is O(n).
- Space complexity is O(1) besides the input array.