The Separate Black and White Balls interview question gives you a binary string where '0' represents a white ball and '1' represents a black ball. You can swap adjacent balls. The goal is to group all black balls to the right and all white balls to the left using the minimum number of adjacent swaps. This is a greedy string sorting problem similar to bubble sort analysis.
Microsoft, Amazon, Google, and Bloomberg ask this problem because it measures the ability to count inversions or derive an optimal swap count analytically rather than simulating all swaps. The greedy insight — each '0' needs to move left past all '1's to its left — yields an O(n) formula based on counting how many '1's precede each '0'. It tests whether candidates can see the mathematical structure behind a seemingly simulation-heavy problem.
The pattern is greedy counting with two-pointer simulation. Track the number of '1's seen so far as you scan left to right. For each '0' encountered, it needs to be swapped past all the '1's before it — this requires exactly count_of_ones_so_far swaps for that '0'. Sum this across all '0's. Alternatively, use two pointers: a left pointer for '0' positions and a right pointer for '1' positions, computing distances.
String: "100110".
Scan left to right:
Minimum swaps: 5.
Final arrangement: "000111".
sorted() gives the final state but doesn't count swaps.For the Separate Black and White Balls coding problem, the two-pointer greedy string interview pattern is the efficient O(n) solution. The key insight is that the minimum number of swaps equals the number of inversions in the binary sequence — pairs where a '1' appears before a '0'. Microsoft and Bloomberg interviewers appreciate when you draw the parallel to bubble sort inversion counting. Practice this: "how many adjacent swaps to sort a binary array?" — it's a classic variation of the minimum swaps problem.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Append Characters to String to Make Subsequence | Medium | Solve | |
| Minimum Adjacent Swaps to Reach the Kth Smallest Number | Medium | Solve | |
| Largest Merge Of Two Strings | Medium | Solve | |
| Lexicographically Smallest Palindrome | Easy | Solve | |
| Valid Palindrome II | Easy | Solve |