Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
LeetCode-283: 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.
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Input: nums = [0]
Output: [0]
Input: nums = [5]
Output: [5]
There are multiple ways to solve this problem.
This approach requires two passes over the array and is not optimal.
Another approach is to use two pointers.
Let’s implement the two-pointer approach to solve this problem.
public void moveZeroes(int[] nums) {
int index = 0;
for(int i=0; i < nums.length; i++){
if(nums[i] != 0){
nums[index] = nums[i];
if(i != index){
nums[i] = 0;
}
index++;
}
}
}
Note that we only increment the index when we encounter a non-zero element. This way, we can maintain the relative order of the non-zero elements.
Also, we set the element at current index i
to 0 only if it is not equal to index
as otherwise it will override the just set value. Consider a single element array for this case: [5]
The time complexity for this approach is $O(n)$, where $n$ is the number of elements in the array. We iterate over the array only once.
Be notified of new posts. Subscribe to the RSS feed.