75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

283. Move Zeroes 🌟

O(N) Time solution

Code

class Solution{
public:
    void moveZeroes(vector<int> &nums)
    {
        int ind = 0, n = nums.size();
        for (int i = 0; i < n; i++)
            if (nums[i] != 0)
                nums[ind++] = nums[i];

        while (ind < n)
            nums[ind++] = 0;
    }
};

O(N) Time snowball solution

Code

class Solution{
public:
    void moveZeroes(vector<int> &nums)
    {
        int snowBallSize=0,n=nums.size();
        for(int i=0; i < n; i++){
            if(nums[i]==0){
                snowBallSize++;
            }
            else{
                int temp=nums[i];
                nums[i]=0;
                nums[i-snowBallSize]=temp;
            }
        }
    }
};

Optimal solution

Code

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size();
        int i = 0, j = 0;
        for(int i = 0;i<n;i++){
            if(nums[i]!=0){
                swap(nums[i],nums[j]);
                j++;
            }
        }
    }
};