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
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
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!