LeetCode 2938, Medium. Topics: Two Pointers, String, Greedy. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 21 parametrized pytest cases, and a playground notebook:
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.
Examples
Constraints
- 1 <= n == s.length <= 10^5
- s[i] is either ‘0’ or ‘1’.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026