Theory to get started
In this approach we take double pointers I
and J
and move them until the end of an array as we come across any index that contains 0
.
Step 1: declare pointer J and initialise it to -1.
Step 2: This is a for-loop where if we find a 0th element, then we assign pointer J to that index I that points to the 0th element.
Step-3: if pointer J returns -1, that means it just returns the default value and there was no 0th element found in an entire array hence return the array as is.
Step 4: Now run a new loop again but this time the starting point should be J+1
the reason being that anything before 0th element has been already shifted.
Continue the steps above until your reach end of an array.
Here is the breakdown of the steps in the code:
/**
* https://leetcode.com/problems/move-zeroes/description/
* Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
*/
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> moveZeroesToEnd(vector<int>& nums){
int ptr_j = -1;
for(int i=0; i < nums.size(); i++){
if(nums[i] == 0){
ptr_j = i;
break;
}
}
if(ptr_j== -1) return nums;
for(int i=ptr_j+1; i < nums.size(); i++){
if (nums[i] != 0){
swap(nums[i], nums[ptr_j]);
ptr_j++;
}
}
return nums;
}
int main(){
int n;
cin >> n;
vector<int> arr(n);
for(int i=0; i < n; i++){
// take array input from the user
cin >> arr[i];
}
vector<int> ans = moveZeroesToEnd(arr);
for (auto &it : ans) {
cout << it << " ";
}
}