ORIGINAL CODING QUESTION
Group active flags with swaps
Swap any two positions per move. Find the fewest swaps needed to place all 1 flags in one contiguous group. Return 0 when there are no 1 flags.
Original exercise · medium. Editorial role relevance does not imply a company has asked this question.
Input and output
n, then n integer values. Print one integer as described.
Constraints
1 ≤ n ≤ 200; each flag is 0 or 1.
Example 1
Input
5 1 0 1 0 1
Output
1
A length-3 block needs one swap.
Example 2
Input
3 0 0 0
Output
0
No active flags need grouping.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
The target block length equals the total count of ones.
Hint 2
Count zeros in each block of that length.
Hint 3
Each zero in the best block can be swapped with a one outside it.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →