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 Balls INPUT Binary String s = "101" 0 1 2 1 0 1 Visual Representation: Black(1) White(0) Black(1) Goal: White balls left, Black balls right n = 3 balls ALGORITHM STEPS Greedy Counting Approach 1 Initialize swaps = 0, whites = 0 2 Scan Left to Right Count whites before blacks 3 For each position i: If 0: whites++ If 1: swaps += whites 4 Trace for "101" i s[i] whites swaps 0 1 0 0 1 0 1 0 2 1 1 1 Black at i=2 needs 1 swap FINAL RESULT One swap needed: Before: "101" Swap positions 0 and 1 After: "011" White left, Blacks right - OK Output: 1 Key Insight: Each black ball (1) must move past all white balls (0) to its left. By counting white balls as we scan, when we hit a black ball, we know exactly how many swaps it needs. Time: O(n) | Space: O(1) - Single pass greedy solution! TutorialsPoint - Separate Black and White Balls | Greedy Counting Approach
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