Move Zeroes
Array, Two Pointers
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:
Solutions
The problem is asking to move all zeros in the given array to the end while maintaining the relative order of the non-zero elements. This means that the sequence of non-zero numbers in the array should remain the same after all the zeros have been moved to the end.
Approach – Brute Force Technique
In the brute force approach, we use a simple bubble sort algorithm to push the zeros to the end of the array.
Steps
Get the length of the array: The variable
n
is assigned the length of thenums
array.Outer loop: The outer loop runs from
i = 0
toi = n - 1
. This loop iterates over each element in the array.Inner loop: The inner loop runs from
j = 0
toj = n - i - 2
. This loop compares each element with its next element.Check for zero: If the current element
nums[j]
is zero, then it needs to be moved to the end.Swap elements: If
nums[j]
is zero, it is swapped with the next elementnums[j + 1]
. This is done by creating a temporary variabletemp
to hold the value ofnums[j]
, then assigningnums[j]
the value ofnums[j + 1]
, and finally assigningnums[j + 1]
the value oftemp
.Repeat: The process is repeated for all elements in the array until all zeros have been moved to the end.
Complexity
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Approach – Two Pointers Technique
In the optimized approach, we keep track of the last non-zero element found in the array. We then swap the current element with the last non-zero element if the current element is non-zero.
Steps
Initialize a pointer: The variable
lastNonZeroFoundAt
is initialized to0
. This pointer will keep track of the position where the next non-zero element should be moved.Iterate through the array: The first
for
loop runs fromi = 0
toi = nums.Length - 1
. This loop iterates over each element in the array.Check if the current element is non-zero: If the current element
nums[i]
is non-zero, then it needs to be moved to the position pointed bylastNonZeroFoundAt
.Move non-zero elements to the front: If
nums[i]
is non-zero, it is moved to the positionnums[lastNonZeroFoundAt]
, and then thelastNonZeroFoundAt
pointer is incremented. This effectively moves all non-zero elements to the front of the array, while maintaining their relative order.Fill the rest of the array with zeros: The second
for
loop runs fromi = lastNonZeroFoundAt
toi = nums.Length - 1
. This loop sets all the remaining elements in the array to zero.
Complexity
Time Complexity: O(n)
Auxiliary Space: O(1)
Last updated