Problem Statement: here
PS Understanding:
In the given array, move all the 0s to the end while maintaining the order of other numbers.
Solution:
We can achieve this by bringing all the non-zero elements to the front of the array.
def moveZeroes(nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
- We scan the array once while keeping pointer j that marks where the next non-zero number should go.
- As we traverse with another pointer i, we swap the non-zero number with the number at position j.
- This ensures that all non-zero elements get shifted forward and j keeps moving to the next position.
- Zeros automatically end up at the back because other numbers keep taking the front positions during the iterations.
Top comments (0)