#2938
Medium Algorithms Separate black and white balls
Two Pointers String Greedy
64.0% acceptance
Feb 25, 2026
878
43
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.
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_steps(s: String) -> i64 {
let mut ones_before = 0i64;
let mut ans = 0i64;
for ch in s.bytes() {
if ch == b'1' {
ones_before += 1;
} else {
ans += ones_before;
}
}
ans
}
}