Minimum Swaps to Group All 1's Together
MediumSliding Windowsliding window
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
You are given a binary array data. In one swap you may exchange the values at any two positions (they do not need to be adjacent).
Return the minimum number of swaps needed so that all 1s in the array sit in one contiguous block, anywhere in the array. If the array has zero or one 1, the answer is 0.
Examples
Input: data = [1,0,1,0,1]
Output: 1
Swap the 0 at index 1 with the 1 at index 4 to get `[1,1,1,0,0]`.
Input: data = [0,0,0,1,0]
Output: 0
There is only one `1`, which is already a block.
Input: data = [1,0,1,0,1,0,0,1,1,0,1]
Output: 3
There are six 1s; the best window of length six contains three 0s, and each needs one swap.
Constraints
- 1 <= data.length <= 10^5
- data[i] is 0 or 1
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.