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:                                                          Example 2: 

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

Output: [1,3,12,0,0]                                           Output: [0]   



 First, i used this     (Two-Pointer Approach)

class Solution {
    public void moveZeroes(int[] nums) {
      int n= nums.length;int j=0;int k=0;
     
      for(int i=0;i<n;i++){
        if(nums[i]==0){
        k++;
        }
        else{
            nums[j]=nums[i];
            j++;
        }
       
      }
      while(k>0){
        nums[n-1]=0;
       n--;
       k--;
      }

    }
}



But this is not optimised.

T.C-o(n^2) S.C-o(1)

Most optimised (Swap Approach) -

class Solution {
    public void moveZeroes(int[] nums) {
      int n= nums.length;int j=0;
     
      for(int i=0;i<n;i++){
        if(nums[i]!=0){
           if(i!=j){
            int temp=nums[i];
            nums[i]=nums[j];
            nums[j]=temp;
           }
           j++;
        }
       
      }
     
    }
}

Let’s take the input:
[0, 1, 0, 3, 12]

1️⃣ i = 0, j = 0nums[i] == 0, so do nothing.
2️⃣ i = 1, j = 0nums[i] == 1 (non-zero), swap nums[0] ↔ nums[1][1, 0, 0, 3, 12]

  • Move j to 1
    3️⃣ i = 2, j = 1nums[i] == 0, so do nothing.
    4️⃣ i = 3, j = 1nums[i] == 3 (non-zero), swap nums[1] ↔ nums[3][1, 3, 0, 0, 12]
  • Move j to 2
    5️⃣ i = 4, j = 2nums[i] == 12 (non-zero), swap nums[2] ↔ nums[4][1, 3, 12, 0, 0]
  • Move j to 3

💡 Final Output: [1, 3, 12, 0, 0]

Comments

Popular Posts