Moves Zeroes | leetcode solution

Efficient  Solution for Moving zeroes to the end of an integer array

Efficient  Solution for Moving zeroes to the end of an integer array

Problem Statement

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

Solution Approach


In the problem statement, we have given an integer array  of nums and we have to move all 0's to the end of the array and also maintain the order of non-zeroes elements 

Here we are going to use the bubble sort algorithm  for a simple understanding 

we have to use also nested loop here 
so my first loop will run till nums.length-2;  
my second loop runs from j=0; to till nums.length-i-2;
then we have to compare the nums of j==0 and then swap it with the temp
and after that return nums;


why does my second loop run till nums.length-i-2;

let nums.length= 5;
 than nums.length-i-2;
         
Now if my i=0;
 then my j will run till 5-0-2= 3;  it will run till 3 ;
Now if my i=1;
then my j will run till 5-1-2=2; it will run till 2 ;
because the last value is already sorted 
hence it can reduce our number of operations 


JavaScript Implementation:

var moveZeroes = function(nums) {
     for(let i=0; i<=nums.length-2; i++){
     
     for(let j=0; j<=nums.length-i-2; j++){
           if(nums[j]==0){
               let temp=nums[j+1];
                  nums[j+1]=nums[j];
                  nums[j]=temp
                 
           }
     }
 }
    return nums;
    
    // bubble sort 
    
};


Time Complexity

The time complexity of this solution is O(n^2), where n is the length of the input array nums. This is because we use nested loops to iterate through the array, and in the worst case, each element needs to be compared and possibly swapped multiple times.

Space Complexity

The space complexity of this solution is O(1), as we do not use any additional data structures that grow with the size of the input array. We perform all operations in place, modifying the input array nums directly.


Conclusion

By using the Bubble Sort algorithm, we efficiently move zeroes to the end of an integer array while maintaining the order of non-zero elements. This approach ensures simplicity and performance, meeting the problem's constraints effectively.


For more insights into algorithms and efficient coding techniques, visit our comprehensive tutorials and guides!



To get now more about bubble sort algorithm  visit


Post a Comment

Previous Post Next Post