Separate Black and White Balls

There are n balls on a table, and each ball is either black or white.

You are given a 0-indexed binary string s of length n, where 1 represents a black ball and 0 represents a white ball.

In each step, you can choose two adjacent balls and swap them.

Return the minimum number of steps needed to group all the black balls to the right and all the white balls to the left.

Example 1
Inputs = "101"
Output1
Swap s[0] and s[1] to get "011", so at least 1 step is required to group all black balls to the right.
Example 2
Inputs = "100"
Output2
Swapping adjacent balls transforms "100" to "010" and then to "001", and the minimum number of steps needed is 2.

Constraints

  • 1 <= n == s.length <= 10^5
  • s[i] is either '0' or '1'.

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate