LC 283. Move Zeros

Nilanjan Deb · April 1, 2020

This is a very easy question. First of all remove all zeros without using extra array(like remove duplicates with O(1) space complexity) and at last add all these zeros. I hope it is a very simple logic and easy to implement.

This is my CPP solution.

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

Time Complexity O(n); Space Complexity O(1);



Dicussion Forum