Arrays and strings · Exercise 11 of 100
Moving Zeroes to the End
Scan the array from left to right and write each nonzero value into the next open slot, starting at the front. This keeps the nonzero values in their original order. Fill the remaining slots with zeroes.
Try it yourself
Move the zeroes in [0, 5, 0, -2, 0, 8] to the end while preserving the order of the other values. Which value now sits immediately before the first zero?
One-step hint
Scan the original list from the right until you reach a nonzero value. Think about where the block of zeroes begins after the move.
Worked solution
- Skip the zeroes and write 5, -2 and 8 into the first three slots in that order.
- Fill the last three slots with zeroes. The first zero follows the third slot, which holds 8.