A factory conveyor belt is monitored by a fixed-length array of sensor readings, listed in belt order from the intake end to the discharge end. A reading of 0 means that slot on the belt is idle. To make idle slots stand out for the downstream vision system, the control software echoes every idle reading the moment it is scanned: whenever it encounters a 0, it inserts one extra 0 immediately after it, shifting every reading that follows one position toward the discharge end. Because the monitoring buffer has a fixed length of n, any reading (including a freshly inserted echo) that would be pushed past the last position is simply dropped rather than kept.
Process the buffer once, left to right starting from the intake end, applying this echo-and-shift rule in place, and report the final n readings.
Example 1
Input
8 1 0 2 3 0 4 5 0
Expected
1 0 0 2 3 0 0 4
Explanation
Scanning left to right: the 0 at index 1 is echoed, shifting everything after it right by one and dropping the last element to keep length 8, giving [1,0,0,2,3,0,4,5]. Continuing, the 0 now at index 5 is echoed the same way, shifting the tail right and dropping the final element again, giving the final buffer [1,0,0,2,3,0,0,4].
Example 2
Input
5 8 0 9 0 0
Expected
8 0 0 9 0
Explanation
The 0 at index 1 is echoed, shifting the rest right and dropping the last value, giving [8,0,0,9,0]. The next zero at index 4 is also echoed, but its duplicate would land at index 5, past the fixed length of 5, so it is discarded and the buffer stays [8,0,0,9,0].
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →