283 Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.
Implementation 2:
The Idea: We can solve this problem purely using iterators and swaps. The general idea is to swap each zero with the first instance of the next number, given that the zero follows the number. Both iterators begin at 0. We continue to increment the left iterator until we find a zero, do so the same with the number iterator. Given that the number and the zero is found and that the zero follows the number, we can swap the two. This way, we preserve the order of the numbers
Complexity: O(n) time (since both iterators do a single scan through the array at most) and O(1) space
Last updated
Was this helpful?