Minimum Adjacent Swaps to Sort a Binary String
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests greedy inversion-counting on a binary string to find the minimum number of adjacent swaps needed to push all 1s to the right.
Problem
You are given a binary string bits made up of the characters '0' and '1'. Your goal is to rearrange it so that every '0' comes before every '1'.
The only operation you may perform is swapping two adjacent characters. Each such swap costs exactly 1. Return the minimum total cost to reach a fully sorted arrangement.
Constraints
1 <= len(bits) <= 10^6bitscontains only the characters'0'and'1'.- An already-sorted string (all
'0's before all'1's) has cost0. - A string with no
'1's, no'0's, or a single character also has cost0. - The result can be as large as roughly
(n/2)^2 ≈ 2.5 × 10^11forn = 10^6, so use a 64-bit integer type in fixed-width languages.
Examples
Example 1
Input: sort_binary_cost('1010')
Output: 3
Example 2
Input: sort_binary_cost('000')
Output: 0
Hints
Hint 1
Count how many '1's appear to the left of each '0'. Each of those '1's must cross that '0' at least once to reach its final position — and exactly once is always achievable with adjacent swaps.
Hint 2
You don't need to simulate the swaps. A single left-to-right pass with one counter for '1's seen so far is enough: every time you encounter a '0', add the running count of '1's to your total.
Hint 3
Think about why each adjacent swap on a '1' followed by a '0' reduces the total work by exactly 1, and why no other swap can ever help. This gives you both the lower bound and the proof that your greedy count is achievable.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: adjacent swaps count inversions
Define an inversion as any pair of positions (i, j) with i < j, bits[i] == '1', and bits[j] == '0'. In the sorted string every '1' sits to the right of every '0', so there are zero inversions. Every inversion in the original string represents one '1' that must eventually move past one '0'.
Each useful swap reduces the inversion count by exactly 1. Swapping an adjacent "10" into "01" eliminates precisely the one inversion between those two positions; every other pair's relative order is untouched. The reverse swap ("01" → "10") would add an inversion, so it can never help.
Lower bound. The target has 0 inversions and each swap removes at most 1, so you need at least I swaps, where I is the initial inversion count.
Achievability. If the string is not yet sorted, some '1' precedes some '0'. Tracing from that '1' toward that '0', the value must drop from 1 to 0 at some adjacent boundary, giving an adjacent "10" to swap. Repeating this always makes progress, so I swaps always suffice.
The minimum cost is therefore exactly the number of inversions.
Single-pass algorithm
Count inversions without comparing all pairs:
- Scan left to right, maintaining
ones= number of'1's seen so far. - When you encounter a
'0', each of thoseonesis an inversion with the current position, so addonestocost.
This counts every (i, j) inversion pair exactly once, in O(n) time.
Worked example
For bits = "1010":
| index | char | ones | cost |
|---|---|---|---|
| 0 | '1' | 1 | 0 |
| 1 | '0' | 1 | 1 |
| 2 | '1' | 2 | 1 |
| 3 | '0' | 2 | 3 |
Result: 3.
Edge cases
- No
'1's or no'0's:onesstays 0 throughout, cost is 0. - Already sorted (
"0011"): every'0'is encountered whileones == 0, cost is 0. - All
'1's before all'0's ("1100"): worst case for a 4-character string;onesis 2 for both'0's, cost is 4. - Single character: the loop runs once and adds nothing, cost is 0.
Complexity
- Time: O(n) — one pass over the string.
- Space: O(1) — two integer counters, no auxiliary structures.
The result can reach (n/2)^2 ≈ 2.5 × 10^11 for n = 10^6. Python handles this natively; in fixed-width languages use a 64-bit integer.
Reference solution
def sort_binary_cost(bits: str) -> int:
ones = 0 # number of '1's seen so far in the left-to-right scan
cost = 0 # accumulated inversion count
for ch in bits:
if ch == '1':
ones += 1
else:
# every '1' to the left of this '0' must cross it exactly once
cost += ones
return cost