Separate Black and White Balls — LeetCode 2938 Python Solution
MediumGreedyTwo PointersString
- Problem
- #2938
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(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
LeetCode 680Valid Palindrome IIEasyLeetCode 942DI String MatchEasyLeetCode 1147Longest Chunked Palindrome DecompositionHardLeetCode 1754Largest Merge Of Two StringsMediumLeetCode 1850Minimum Adjacent Swaps to Reach the Kth Smallest NumberMediumLeetCode 2193Minimum Number of Moves to Make PalindromeHard
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.