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
๐ŸŽณ Ball Separation StrategyExample: "11100" โ†’ "00111"Each black ball must jump over white balls to its leftStep 1: Scan "1" at pos 011100White count: 0, Swaps: 0Step 4: Scan "0" at pos 311100White count: 1, Swaps: 0Final Result00111Total swaps: 6๐Ÿ’ก Key InsightFor string "11100":โ€ข 1st black ball: 0 whites to left โ†’ 0 swapsโ€ข 2nd black ball: 0 whites to left โ†’ 0 swapsโ€ข 3rd black ball: 0 whites to left โ†’ 0 swapsโ€ข 1st white ball: just count itโ€ข 2nd white ball: just count it
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!
Asked in
Google 45 Amazon 32 Microsoft 28 Meta 15
38.9K Views
Medium Frequency
~15 min Avg. Time
1.5K 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