Separate Black and White Balls

Medium Topics Company Tags

The string s describes a row of balls: 0 is white and 1 is black. In one move, swap two neighboring balls. Return the fewest moves needed to put all white balls to the left of all black balls. The result can exceed the signed 32-bit integer range.

Example 1:

Input: s = "1100"

Output: 4

Explanation: Each of the two white balls, represented by 0, must pass both black balls. This requires 2 + 2 = 4 adjacent swaps.

Example 2:

Input: s = "1010"

Output: 3

Explanation: The first white ball must pass one black ball, and the second must pass two. The total is 1 + 2 = 3 adjacent swaps.

Example 3:

Input: s = "000111"

Output: 0

Explanation: Every white ball is already to the left of every black ball, so no swaps are needed.

Constraints:

  • 1 <= s.length <= 100000
  • Each character is 0 or 1.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.