2938. Separate Black and White Balls #703
-
Topics: There are You are given a 0-indexed binary string 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. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To solve this problem efficiently, we can use a greedy approach with a two-pointer-like strategy. The key insight is that every Approach
Let's implement this solution in PHP: 2938. Separate Black and White Balls <?php
/**
* @param String $s
* @return Integer
*/
function minSwapsToGroupBlackBalls($s) {
$n = strlen($s);
$zeroCount = 0; // Tracks the number of '0's encountered
$swaps = 0; // Tracks the minimum number of swaps needed
// Iterate through the string from right to left
for ($i = $n - 1; $i >= 0; $i--) {
if ($s[$i] == '0') {
// Increment the count of zeros when encountering '0'
$zeroCount++;
} elseif ($s[$i] == '1') {
// When encountering '1', add the count of '0's to swaps
$swaps += $zeroCount;
}
}
return $swaps;
}
// Example usage
$s1 = "101";
echo "Input: $s1\n";
echo "Minimum swaps needed: " . minSwapsToGroupBlackBalls($s1) . "\n"; // Output: 1
$s2 = "100";
echo "Input: $s2\n";
echo "Minimum swaps needed: " . minSwapsToGroupBlackBalls($s2) . "\n"; // Output: 2
$s3 = "0111";
echo "Input: $s3\n";
echo "Minimum swaps needed: " . minSwapsToGroupBlackBalls($s3) . "\n"; // Output: 0
?> Explanation:
Time Complexity
Example Analysis
This solution provides an efficient way to determine the minimum steps to separate black and white balls using PHP. |
Beta Was this translation helpful? Give feedback.
To solve this problem efficiently, we can use a greedy approach with a two-pointer-like strategy. The key insight is that every
1
(black ball) should be moved past the0
s (white balls) that are to its right, minimizing the total number of swaps.Approach
Track the Number of
0
s Encountered:0
s encountered so far as you iterate.1
, each0
that is to its right contributes to a swap needed to move this1
past those0
s.0
s to the total swaps each time you encounter a1
.Calculate the Total Swaps:
0
s encountered when …