Notice Period

Shelve the Blanks

easy

A warehouse shelf is logged as a list of item codes, where 0 marks an empty slot. The picker wants all real items slid to the front — keeping their relative order — and all the empty slots pushed to the back, so one walk down the shelf grabs everything.

Given the list shelf, rearrange it so every nonzero value keeps its original order at the front and all zeros sit at the end. Return the rearranged list. Do it in place with O(1) extra space — no second list.

Example 1
in shelf = [0, 4, 0, 7, 12]
out [4, 7, 12, 0, 0]
4, 7, 12 keep their order; the two empties move to the back.
Example 2
in shelf = [3, 1]
out [3, 1]
No empty slots — nothing to do.
Constraints
  • · 1 <= len(shelf) <= 10^5
  • · -10^9 <= shelf[i] <= 10^9
  • · O(1) extra space
similar problem on LeetCode ↗
solution.pyloading python…
test results
Hit ▶ Run to test your code against the visible cases.