LeetCode 283: Move Zeroes

ArrayTwo Pointers

Problem Description

Explanation

To solve this problem, we can use a two-pointer approach. We maintain two pointers, left and right, where left points to the next position to store a non-zero element, and right iterates through the array. As right iterates through the array, if we encounter a non-zero element, we swap it with the element at the left pointer and increment left. By doing this, we are moving all non-zero elements to the beginning of the array while maintaining their relative order. Finally, we fill the rest of the array with zeroes.

  • Time complexity: O(n), where n is the number of elements in the array.
  • Space complexity: O(1), as we are modifying the input array in-place.

Solutions

class Solution {
    public void moveZeroes(int[] nums) {
        int left = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] != 0) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
            }
        }
    }
}

Loading editor...