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
Problem: 283. Move Zeroes / Move Zeroes To End
Problem Link:
Companies Asked: TCS, IBM, Uber, Apple, Adobe, Amazon, Yandex, Tiktok, Expedia, Facebook, Microsoft, Bloomberg
Approach:
Initiate a variable called fillPointer.
Traverse through the given array.
Once a non-zero element is encountered create insert arr[i] into arr[fillPointer].
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;
}
}
};