Separate Black and White Balls - Problem
๐ดโซ Separate Black and White Balls
Imagine you have n balls arranged in a line on a table, where each ball is either black (1) or white (0). You're given a binary string s of length n representing this arrangement.
Your goal is to rearrange the balls so that:
- All white balls (0s) are grouped on the left side
- All black balls (1s) are grouped on the right side
The only operation allowed is to swap two adjacent balls in each step. Find the minimum number of swaps needed to achieve this separation.
Example: "101" โ "011" requires 1 swap (swap positions 0 and 1)
Input & Output
example_1.py โ Basic case
$
Input:
s = "101"
โบ
Output:
1
๐ก Note:
We can swap positions 0 and 1: "101" โ "011". The black ball at position 0 needs to jump over 1 white ball.
example_2.py โ Multiple swaps
$
Input:
s = "100"
โบ
Output:
2
๐ก Note:
The black ball at position 0 needs to move past 2 white balls: "100" โ "010" โ "001". Total: 2 swaps.
example_3.py โ Already sorted
$
Input:
s = "0011"
โบ
Output:
0
๐ก Note:
Already in correct order (white balls left, black balls right). No swaps needed.
Constraints
- 1 โค n โค 105
-
s[i]is either '0' or '1' - The string contains at least one character
Visualization
Tap to expand
Understanding the Visualization
1
Count White Balls
As we scan left to right, keep count of white balls (0s) seen
2
Process Black Balls
When we see a black ball (1), it must pass all white balls to its left
3
Add to Result
Add the white ball count to our total swaps - that's exactly how many swaps this black ball needs
4
Continue Scanning
Repeat for all characters in the string
Key Takeaway
๐ฏ Key Insight: Each black ball must cross exactly all white balls to its left - count these crossings efficiently in one pass!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code