Move Zeroes
Problem
Given an integer array nums
, move all 0
’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Follow up: Could you minimize the total number of operations done?
Constraints
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Solution
The problem Move Zeroes
can be solved using a sliding window technique by tracking the position of the first occurrence of 0
from the array with a left
index and the position of the first non zero element starting from the left
index with a right
index. By swapping elements at left
and right
indexes until the right
index reaches the end, all 0
’s can be moved to the end while also maintaining the relative order of the non-zero elements.
Implementation
class Solution
{
public:
void moveZeroes(vector<int> &nums)
{
int left = 0;
while (left < nums.size() - 1 && nums[left] != 0)
left += 1;
int right = left + 1;
while (right < nums.size())
{
while (right < nums.size() - 1 && nums[right] == 0)
right += 1;
swap(nums[left++], nums[right++]);
}
}
};