Separate Black and White Balls - Problem

There are n balls on a table, each ball has a color black or white. You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

In each step, you can choose two adjacent balls and swap them. Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

Input & Output

Example 1 — Basic Mixed Sequence
$ Input: s = "101"
Output: 1
💡 Note: We can group all black balls to the right by swapping s[0] and s[1]: "101" → "011". This takes 1 step.
Example 2 — Multiple Swaps Needed
$ Input: s = "0110"
Output: 2
💡 Note: We can group all black balls to the right in 2 steps: "0110" → "1010" → "1100". The white ball at index 0 needs 2 swaps to move past both black balls.
Example 3 — Already Sorted
$ Input: s = "0011"
Output: 0
💡 Note: All white balls are already on the left and black balls on the right. No swaps needed.

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Separate Black and White BallsInput: "0110"0110Adjacent swaps onlyGoal: "1100"1100Solution Process• Scan right to left: count black balls• For each white ball: add black count to totalOutput: 2 swaps needed
Understanding the Visualization
1
Input
Mixed sequence of black (1) and white (0) balls
2
Process
Count minimum adjacent swaps needed
3
Output
Number of swaps to group whites left, blacks right
Key Takeaway
🎯 Key Insight: Each white ball must pass all black balls to its right - count blacks while scanning backwards
Asked in
Meta 25 Google 20 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen