Separate Black and White Balls (LeetCode 2938): Solution and Explanation
Given a binary string where 1 is a black ball and 0 is a white ball, return the fewest adjacent swaps needed to move every black ball to the right of every white ball.
Intuition
Look at what a useful swap does: a black ball and the white ball right after it trade places. That moves one white ball one step left past one black ball.
In the final row the white balls sit at indices 0, 1, 2 and so on, in the same order they started. So the k-th white ball has to travel from its starting index to index k.
That distance is exactly the number of black balls in front of it, and each of those black balls has to be crossed by one swap. Adding the distances gives the answer, and no plan can use fewer swaps.
Approach: Slide each white ball to its slot
- Set
steps = 0andslot = 0(where the next white ball belongs). - Scan
ifrom left to right. - If
s[i] == '0', addi - slottostepsand incrementslot. - Black balls need no action; they are pushed right by the white balls that pass them.
- Return
stepsas a 64-bit integer.
Step-by-step example
s = "100"
- i = 0 is black. slot stays 0.
- i = 1 is white. It slides from 1 to slot 0, passing one black ball: steps = 1, slot = 1.
- i = 2 is white. It slides from 2 to slot 1, passing the same black ball: steps = 2, slot = 2.
- The row is now "001", and the answer is 2.
Code: Python, Java, C++
1class Solution:
2 def minimumSteps(self, s: str) -> int:
3 steps = 0
4 slot = 0
5 for i, ch in enumerate(s):
6 if ch == '0':
7 steps += i - slot
8 slot += 1
9 return steps1class Solution {
2 public long minimumSteps(String s) {
3 long steps = 0;
4 int slot = 0;
5 for (int i = 0; i < s.length(); i++) {
6 if (s.charAt(i) == '0') {
7 steps += i - slot;
8 slot++;
9 }
10 }
11 return steps;
12 }
13}1class Solution {
2public:
3 long long minimumSteps(string s) {
4 long long steps = 0;
5 int slot = 0;
6 for (int i = 0; i < (int)s.size(); i++) {
7 if (s[i] == '0') {
8 steps += i - slot;
9 slot++;
10 }
11 }
12 return steps;
13 }
14};Time and space complexity
O(n)
One pass over the string with constant work per ball.
O(1)
Only steps and slot are stored.
Other approaches
Count black balls seen (time O(n), space O(1))
Keep a running count of 1s; each 0 adds that count to the answer. It is the same sum seen from the black balls' side: i - slot equals the number of 1s before i.
Simulate bubble sort (time O(n^2), space O(n))
Repeatedly swap any adjacent "10" pair and count swaps. It reaches the right number but takes O(n^2) time, far too slow for 10^5 balls.
Common mistakes
- Using a 32-bit integer. With 50,000 black balls followed by 50,000 white ones the answer is 2.5 billion, which overflows int.
- Counting how many balls are out of place instead of how far they travel. "100" has two misplaced white balls but needs only 2 swaps because both pass the same single black ball; "1100" needs 4.
- Adding i instead of i - slot. White balls that are already packed on the left still count as occupying slots, so a white ball only travels past the black balls in front of it.
- Treating the swap as free to pick any two balls. Only adjacent balls can be swapped, which is why each swap removes exactly one black-before-white pair.
Frequently asked questions
Why is the sum of distances the minimum?
Every pair with a black ball before a white ball must be fixed, and one adjacent swap fixes at most one such pair. The sum of distances equals the number of these pairs, and the greedy plan fixes one pair with every swap, so it meets the lower bound.
Where are the two pointers?
i scans the original row and slot marks the left boundary of the packed white section. slot trails i, and the gap between them is how far the current white ball slides.
Would scanning for black balls from the right give the same answer?
Yes. Each black ball must slide right past the white balls after it, and summing those distances counts the same black-before-white pairs.