Question 10 of 75 - LeetCode Weekly Challenge

LeetCode Challenge #283. Move Zeroes

Given an integer array nums, move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

 

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]
Output: [0]

 

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1
Video Solution
C++ Solution
				
					class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int i=0,j=0;
        while(j<nums.size())
        {
            if(nums[j]!=0)
            {
                swap(nums[i],nums[j]);
                i++;
            }
             j++;
        }
    }
}
				
			
Code Explanation

The purpose of this function is to move all the zeroes to the end of the list while keeping the numbers in the same order.

Let’s see the approach to this problem:

  1. We will use two-pointer approach towards this problem 

Initialise two variables, ‘i’ and ‘j’, both set to 0. These variables are used to iterate through the vector.

  1. Using a ‘while’ loop that continues until ‘j’ reaches the end of vector (‘nums.size()’) 

Inside the loop, we check 

  • If we get a non-zero element through ‘j’ then ‘swap’ i and j position (swap the elements). And increment i (i++) 
  • And when ‘j’ is  0. It will just increment. And now ‘j’ is a non-zero element then increment j ( j ++) and then “swap” j and i.
  1. In this way, all the zeroes will move to the end and all the non-zeros elements will move to the front of vector. 
  1. The loop will continue until ‘j’ reaches the end of the list. 

And our result will be obtained. 

It’s like organizing a line of numbers. The non-zero numbers go to the front, and all the zeros naturally end up at the back.

Happy Coding with edSlash