Skip to content

Practice Separate Black and White Balls

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#2938
LeetCode Problem

Separate Black and White Balls

Problem Statement

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, respectively. 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.

Source: Separate Black and White Balls on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
s = "101"
Output
1

# Example 2

Input
s = "100"
Output
2

# Example 3

Input
s = "0111"
Output
0

Constraints

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

Related LeetCode Problems

Practice more problems similar to Separate Black and White Balls.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.