Leetcode 2938: Separate Black and White Balls

grid47
grid47
Exploring patterns and algorithms
Jan 18, 2024 5 min read

You are given a binary string s of length n, where each character represents a ball: ‘1’ for black and ‘0’ for white. The goal is to arrange the balls such that all the white balls are on the left side and all the black balls are on the right side, by swapping two adjacent balls in each step. You need to find the minimum number of adjacent swaps required to achieve this arrangement.
Problem
Approach
Steps
Complexity
Input: You are given a binary string s of length n where each character is either '1' or '0'.
Example: s = '110'
Constraints:
• 1 <= n <= 10^5
• s[i] is either '0' or '1'.
Output: Return the minimum number of adjacent swaps required to group all black balls to the right and all white balls to the left.
Example: For s = '110', the output is 1.
Constraints:
Goal: The goal is to determine the minimum number of adjacent swaps required to sort all black balls to the right and all white balls to the left.
Steps:
• Iterate through the string while counting the number of white balls ('0') encountered.
• For each black ball ('1'), count how many white balls are to the left of it, as this indicates how many swaps are needed to move the black ball to its correct position.
Goal: The string must contain at least one ball and no more than 100,000 balls.
Steps:
• 1 <= n <= 10^5
• Each character in s is either '0' or '1'.
Assumptions:
• The string contains at least one ball, and no more than 100,000 balls.
Input: s = '110'
Explanation: One swap is needed to move the black ball at position 1 to the right.

Input: s = '01010'
Explanation: Four swaps are needed to move all black balls to the right.

Input: s = '000111'
Explanation: No swaps are needed because all black balls are already grouped to the right.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus