Separate Black and White Balls — LeetCode 2938 Python Solution

MediumGreedyTwo PointersString
Problem
#2938
Reading time
2 min

The problem

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.

Example

Input
s = "101"
Output
1
Explanation
We can group all the black balls to the right in the following way:

Python solution

Python
class Solution:
    def minimumSteps(self, s: str) -> int:
        n = len(s)
        ans = cnt = 0
        for i in range(n - 1, -1, -1):
            if s[i] == '1':
                cnt += 1
                ans += n - i - cnt
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2938. Separate Black and White Balls is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2938. Separate Black and White Balls?
LeetCode 2938. Separate Black and White Balls is rated Medium on LeetCode.
What is the time complexity of LeetCode 2938. Separate Black and White Balls?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 2938. Separate Black and White Balls?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2938. Separate Black and White Balls cover?
LeetCode 2938. Separate Black and White Balls is tagged Greedy, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview