JavaScriptEasyArrays10 min
Move zeroes to the end
Move all zeroes after the nonzero values while retaining the relative order of nonzero values. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess compact nonzero elements with a write pointer.
Input
A JSON array of integers on stdin.
Output
Print one compact JSON value: an array of integers.
Constraints
0 <= array length <= 10000; integers between -1000000 and 1000000.
Example
Input
[0,1,0,3,12]
Output
[1,3,12,0,0]
Example 2 input
[0,0]
Output
[0,0]
Boundary case: Fill the remaining positions with zero
Public test cases (2)
Input
[0,1,0,3,12]
Expected output
[1,3,12,0,0]
Input
[1,2]
Expected output
[1,2]
Hints (2)
- Write each nonzero value to the next available position
- Fill the remaining positions with zero
Target complexity: time O(n) · space O(1) excluding the input/output array
