⬅ Previous Topic
Left Rotate an Array by K PlacesNext Topic ⮕
Linear Search in Array⬅ Previous Topic
Left Rotate an Array by K PlacesNext Topic ⮕
Linear Search in ArrayTopic Contents
Given an array of integers, your task is to move all the zeroes to the end of the array, while maintaining the relative order of non-zero elements.
This must be done in-place without making a copy of the array, and ideally in a single pass using an optimal approach.
If the array is empty, return it as is.
arr
.nonZeroIndex
to 0.arr[nonZeroIndex]
and increment nonZeroIndex
.nonZeroIndex
to the end with zeroes.def move_zeroes(arr):
nonZeroIndex = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[nonZeroIndex] = arr[i]
nonZeroIndex += 1
for i in range(nonZeroIndex, len(arr)):
arr[i] = 0
return arr
# Sample Input
arr = [0, 1, 0, 3, 12]
print("Result:", move_zeroes(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Even if no zeros are present, the algorithm still iterates through the entire array once to check each element. |
Average Case | O(n) | The algorithm goes through the array once to move non-zero elements and then fills the remaining positions with zeroes. |
Average Case | O(n) | When all elements are zero or all are non-zero, the algorithm still performs a full scan and update in two linear passes. |
O(1)
Explanation: The algorithm performs all operations in-place using a constant number of variables, without using any extra space.
Let's move all zeroes to the end while maintaining the order of non-zero elements.
Initialize nonZeroIndex = 0
. We'll use this to track where the next non-zero element should go.
Element is 0
. It's zero. Do nothing and move to next.
Element is 1
. It's non-zero, so move it to index 0
.
Element is 0
. It's zero. Do nothing and move to next.
Element is 3
. It's non-zero, so move it to index 1
.
Element is 12
. It's non-zero, so move it to index 2
.
[1,3,12,0,0]
⬅ Previous Topic
Left Rotate an Array by K PlacesNext Topic ⮕
Linear Search in ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.