Skip to content

283. Move Zeroes

INFO

Problem: Move Zeroes

Pattern: In-place array mutation / two pointers

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:

  1. left points to the position where the next non-zero value should go.
  2. right scans through the array.
  3. When left already points to a non-zero value, advance it.
  4. When right finds a non-zero value and left points to zero, swap them.
  5. Continue until right reaches 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]

Released under the MIT License.