Bakery Tray Gaps

Easytwo pointersAlso known as Move Zeroes

A bakery's display tray is one long row of slots. Each slot holds a pastry, written as its product number, or is empty, written as 0. As customers buy things during the morning, gaps open up all over the tray.

Before the lunch rush, the baker slides every pastry toward the front of the tray so the gaps collect at the back, where the new batch will go. The pastries must stay in the same order as before, because the labels on the glass follow that order.

Your task

Write compactTray(tray). Rearrange tray in place so all non-zero numbers come first, in their original order, followed by all the zeros. Return nothing.

Do not create a second list. The length of tray stays the same.

compactTray(tray: int[]) → void (changes tray in place)

Examples

Example 1
Input
tray = [0, 41, 0, 7, 12]
Output
[41, 7, 12, 0, 0]
Why

The pastries are 41, 7, 12, in that order. They move to the front and keep that order. The two gaps end up at the back.

Example 2
Input
tray = [9, 3, 0, 0, 5]
Output
[9, 3, 5, 0, 0]
Why

9 and 3 are already in place. Only 5 has to move forward, past the two gaps. Sorting would give a different, wrong answer: the order 9, 3, 5 must be kept.

Constraints

  • 0 ≤ tray.length ≤ 10,000
  • 0 ≤ tray[i] ≤ 999
Start with brute force

Each time you find a gap, delete it from the list and add a 0 at the end. Or, scan for the first gap and shift everything after it one place left, again and again.

Both are correct, but each delete or shift moves every later slot. A tray of 10,000 slots that is half gaps does about 5,000 shifts of up to 10,000 slots each: tens of millions of moves. Each pastry only needs to move once, straight to its final slot.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code