# 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.

Example:

Input: [0,1,0,3,12]
Output: [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.

# Solution

Approach 1: Two pointers with sub-optimal operation.

Approach 2: Two pointers with optimal operation.

# Code (Python)

Approach 2:

    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        slot = 0
        for current in range(len(nums)):
            if nums[current] != 0:
                nums[current], nums[slot] = nums[slot], nums[current]
                slot += 1

# Code (C++)

Approach 1:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int slow = 0;
        int fast = 0;
        while (fast < nums.size())
        {
            if (nums[fast] != 0)
            {
                nums[slow] = nums[fast];
                slow++;
            }
            fast++;
        }
        while (slow < nums.size())
        {
            nums[slow] = 0;
            slow++;
        }
    }
};

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int nonZeroIdx = 0;
        for (int i = 0; i < nums.size(); ++i)
        {
            while (nonZeroIdx < nums.size() && nums[nonZeroIdx] == 0)
            {
                nonZeroIdx++;
            }
            if (nonZeroIdx < nums.size())
            {
                nums[i] = nums[nonZeroIdx];
                nonZeroIdx++;
            }
            else
                nums[i] = 0;
        }
    }
};

Approach 2:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int slow = 0;
        int fast = 0;
        while (slow < nums.size() && fast < nums.size())
        {
            if (nums[slow] == 0 && nums[fast] != 0)
                std::swap(nums[slow], nums[fast]);
            if (nums[slow] != 0)
                slow++;
            fast++;
        }
    }
};