hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Move Zeroes


  • Approach:

    1. Initiate a variable called fillPointer.

    2. Traverse through the given array.

    3. Once a non-zero element is encountered create insert arr[i] into arr[fillPointer].

    4. Increase fillPointer by 1.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(1)


Code [C++]

class Solution {

public:

void moveZeroes(vector<int>& arr) {

int n = arr.size();

int fillPointer = 0;

for(int i=0; i<n; i++){

if(arr[i] != 0){

arr[fillPointer++] = arr[i];

}

}

for(int i=fillPointer; i<arr.size(); i++){

arr[i] = 0;

}

}

};