easyTwo PointersPure DSA~13 min
Compact Inactive Flags
A feature-flag array uses 0 for an inactive slot. To compact storage, push every inactive slot to the end while preserving the relative order of the active flags — done in place.
Problem
Given an integer array nums, move all 0s to the end while keeping the relative order of the non-zero elements. Do this in place without making a copy.
Input
An array nums of n integers (1 ≤ n ≤ 10^4).
Output
The same array mutated so non-zeros keep order and 0s trail.
Constraints
- Must operate in place — O(1) extra space
- Relative order of non-zero elements is preserved
- 1 ≤ nums.length ≤ 10,000
Examples
Example 1
Input
[0,1,0,3,12]
Output
[1,3,12,0,0]
Non-zeros keep order; both zeros move to the end.
Example 2
Input
[0]
Output
[0]
A single zero is already compacted.