Challenge: Zeros to the Back
Completed
Read a list of numbers and move all zeros to the end, keeping the order of the other numbers. Do it in place with a slow and a fast pointer. Print the result separated by spaces.
Input
One line of whole numbers.
Output
The rearranged numbers.
Example
Input
0 5 0 3 12
Output
5 3 12 0 0
Editor
Python
Hints
slow = where the next non-zero number should go.
When nums[fast] isn't 0, swap it into position slow.
Solution explanation
Non-zero numbers are swapped forward in their original order; zeros drift to the back.
Show solution
nums = list(map(int, input().split()))
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
print(" ".join(map(str, nums))) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module