283. Move Zeroes
Move Zeroes asks us to move all zero values to the end of the array while keeping the relative order of non-zero values. The operation must happen in-place, so creating a separate output array is not the intended solution.
Approach
Use two pointers:
leftpoints to the position where the next non-zero value should go.rightscans through the array.- When
leftalready points to a non-zero value, advance it. - When
rightfinds a non-zero value andleftpoints to zero, swap them. - Continue until
rightreaches the end.
The result keeps non-zero values in their original order because each non-zero value is moved forward as it is discovered.
Swift Notes
Swift arrays support in-place swaps with swapAt(_: _:). Because the input is passed as inout, the function can mutate the original array directly.
The implementation below uses left and right indexes and updates them carefully so no extra array is needed.
Complexity
- Time complexity:
O(n). - Space complexity:
O(1).
Edge Cases
- An array with only zeros should stay valid.
- An array with no zeros should remain unchanged.
- A single-element array should not crash or perform unnecessary work.
swift
class Solution {
func moveZeroes(_ nums: inout [Int]) {
var left = 0
var right = 1
while right < nums.count {
if nums[left] != 0 {
left = left + 1
} else if nums[right] != 0 {
nums.swapAt(left, right)
left = left + 1
}
right = right + 1
}
}
}
var solution = Solution()
var testcase1 = [0,1,0,3,12]
solution.moveZeroes(&testcase1)
print(testcase1) // [1,3,12,0,0]
var testcase2 = [0]
solution.moveZeroes(&testcase2)
print(testcase2) // [0]