Separate Black and White Balls

medium two pointers string greedy

Problem

You are given a binary string s where 1 is a black ball and 0 is a white ball. In one step you may swap two adjacent balls. Return the minimum number of steps to move all black balls (1) to the right and all white balls (0) to the left.

Key insight: a black ball at index i must cross every white ball that lies to its right. Equivalently, each white ball must be passed by every black ball sitting to its left, and adjacent swaps move a ball exactly one position — so the answer is the sum of those crossings.

Inputs = "101"
Output1
Swap s[0] and s[1] to get "011". The single 0 at index 1 has one 1 to its left, so it takes 1 step.

def minimumSteps(s: str) -> int:
    ones = 0       # number of 1s (black balls) seen so far
    steps = 0      # running answer
    for ch in s:
        if ch == '1':
            ones += 1            # one more black ball on the left
        else:                    # ch == '0', a white ball
            steps += ones        # every left 1 must cross this 0
    return steps
function minimumSteps(s) {
  let ones = 0;          // number of 1s (black balls) seen so far
  let steps = 0;         // running answer (use BigInt for huge inputs)
  for (const ch of s) {
    if (ch === '1') {
      ones += 1;         // one more black ball on the left
    } else {             // ch === '0', a white ball
      steps += ones;     // every left 1 must cross this 0
    }
  }
  return steps;
}
long minimumSteps(String s) {
    long ones = 0;            // number of 1s (black balls) seen so far
    long steps = 0;           // running answer
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '1') {
            ones++;           // one more black ball on the left
        } else {              // '0', a white ball
            steps += ones;    // every left 1 must cross this 0
        }
    }
    return steps;
}
long long minimumSteps(string s) {
    long long ones = 0;       // number of 1s (black balls) seen so far
    long long steps = 0;      // running answer
    for (char ch : s) {
        if (ch == '1') {
            ones++;           // one more black ball on the left
        } else {              // '0', a white ball
            steps += ones;    // every left 1 must cross this 0
        }
    }
    return steps;
}
Time: O(n) Space: O(1)