KatInterview

Minimum Adjacent Swaps to Sort a Binary String

Greedy & IntervalsAuto-graded · 22 test cases
HardAuto-gradedGreedy & Intervalsgreedystringsinversion-count

Last 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^6
  • bits contains only the characters '0' and '1'.
  • An already-sorted string (all '0's before all '1's) has cost 0.
  • A string with no '1's, no '0's, or a single character also has cost 0.
  • The result can be as large as roughly (n/2)^2 ≈ 2.5 × 10^11 for n = 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.