DEV Community

Mayank Arora
Mayank Arora

Posted on

283. Move Zeroes [Leetcode][C++]

All suggestions are welcome. Please upvote if you like it. Thank you.


Leetcode Problem Link: 283. Move Zeroes


Brute Force Solution:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
    // Brute Force Solution Time O(N) & Auxiliary Space O(N)
    vector<int> a;
    int count=0;
    for(int i=0;i<nums.size();i++){
        if(nums[i]==0)
            count++;
        else
            a.push_back(nums[i]);
    }
    while(count--)
        a.push_back(0);
    for(int i=0;i<nums.size();i++){
        nums[i]=a[i];
    } 
  }
};

Enter fullscreen mode Exit fullscreen mode

Efficient Solution:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
    // Efficient Solution Time O(N) & Auxiliary Space O(1)
    int lt=0,rt=0,n=nums.size();
    while(rt<n){
         if(nums[rt]==0)
              rt++;
         else{
              int temp=nums[lt];
              nums[lt]=nums[rt];
              nums[rt]=temp;
              lt++;
              rt++;
            }
        }
    }
};

Enter fullscreen mode Exit fullscreen mode

All suggestions are welcome. Please upvote if you like it. Thank you.

Top comments (0)