Skip to content

2938. Separate Black and White Balls 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  long long minimumSteps(string s) {
    long ans = 0;
    int ones = 0;

    for (const char c : s)
      if (c == '1')
        ++ones;
      else  // Move 1s to the front of the current '0'.
        ans += ones;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public long minimumSteps(String s) {
    long ans = 0;
    int ones = 0;

    for (final char c : s.toCharArray())
      if (c == '1')
        ++ones;
      else // Move 1s to the front of the current '0'.
        ans += ones;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def minimumSteps(self, s: str) -> int:
    ans = 0
    ones = 0

    for c in s:
      if c == '1':
        ones += 1
      else:  # Move 1s to the front of the current '0'.
        ans += ones

    return ans