Move Zeroes

Move all zeroes in an array to the end while maintaining the relative order of non-zero elements.

Two-Pointer Solution

This problem employs the two-pointer technique, similar to Remove Duplicates from Sorted Array. The first pass collects all non-zero elements, and the second pass fills the remainder with zeroes.

#include <vector>
using namespace std;
 
class Solution {
public:
  void moveZeroes(vector<int> &nums) {
    int i = 0;
    for (int j = 0; j < nums.size(); j++) {
        if(nums[j] != 0){
            nums[i] = nums[j];
            i++;
        }
    }
    for(;i<nums.size();i++){
        nums[i] = 0;
    }
  }
};