Bakery Tray Gaps

Easytwo pointersAlso known as Move Zeroes

A bakery's display tray is one row of slots. Each holds a pastry, written as its product number, or is empty, written as 0. Morning sales leave gaps all over it.

Before lunch, the baker slides every pastry to the front so the gaps collect at the back for the new batch. The pastries keep their order, because the labels on the glass follow it.

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 41, 7, 12 move to the front in 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 moves forward past the two gaps. Sorting would be wrong: 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 and add a 0 at the end. Or shift everything after the first gap one place left, again and again.

Both are correct, but every delete or shift moves all later slots: on a 10,000-slot tray that is half gaps, about 5,000 shifts of up to 10,000 slots. 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