You are given an array of integers. You need to move all the zeroes to the end of the array while maintaining the relative order of the non-zero elements.
Write a function moveZeroes
to solve this problem. The function should take in an array of integers and modify the array in-place.
Input:
[0, 1, 0, 3, 12]
Output:
[1, 3, 12, 0, 0]
We can solve this problem using the Two Pointers technique. We will maintain two pointers, left
and right
.
left
to 0 and right
to 0.right
pointer.right
pointer is non-zero:
left
and right
pointers.left
and right
pointers.right
pointer is zero, simply increment the right
pointer.right
pointer reaches the end of the array.The time complexity for this approach is O(n), where n is the length of the input array. We have to iterate through the array once to move the zeroes.
The space complexity is O(1) as we are modifying the input array in-place.
def moveZeroes(nums):
left = 0
right = 0
while right < len(nums):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
Here is the implementation of the moveZeroes
function in Python:
def moveZeroes(nums):
left = 0
right = 0
while right < len(nums):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
Let's test the function implementation using the example given in the question:
nums = [0, 1, 0, 3, 12]
moveZeroes(nums)
print(nums) # Output: [1, 3, 12, 0, 0]
The output matches the expected result, so the function seems to be working correctly.