← DiffPush

Move 0's to end

Baseline Arrays · Easy O(n) · O(1)

Pushing Empty Slots to the Tail of the Packet Buffer

A network filter stores parsed packets in a fixed buffer where dropped frames are recorded as zero-length entries. Downstream code reads the buffer linearly and expects only real packets at the front, with the empty placeholders swept to the tail. Rearrange the buffer in place without allocating a second one.

Input: An array nums of n integers, where 0 marks an empty slot.

Output: The same array with all real packets kept in their original relative order at the front and every 0 pushed to the end.

Constraints

Examples

Example 1

Input: {"nums":[0,1,0,3,12]}
Output: [1,3,12,0,0]
The real packets 1, 3, 12 keep their order at the front and both zeros land at the tail.

Example 2

Input: {"nums":[0]}
Output: [0]
A buffer holding only an empty slot is already in its final state.

Solve this in your browser →

Also on LeetCode ↗