1963. Minimum Number of Swaps to Make the String Balanced #678
-
Topics: You are given a 0-indexed string A string is called balanced if and only if:
You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a two-pointers approach, which is efficient given the constraints. Approach:
Let's implement this solution in PHP: 1963. Minimum Number of Swaps to Make the String Balanced <?php
/**
* @param String $s
* @return Integer
*/
function minSwaps($s) {
$balance = 0;
$max_imbalance = 0;
// Traverse through the string
for ($i = 0; $i < strlen($s); $i++) {
if ($s[$i] == '[') {
$balance++;
} else {
$balance--;
}
// Track the maximum imbalance
if ($balance < 0) {
$max_imbalance = max($max_imbalance, -$balance);
}
}
// Calculate the number of swaps needed
return ($max_imbalance + 1) / 2;
}
// Example usage:
$s1 = "][][";
echo minSwaps($s1); // Output: 1
$s2 = "]]][[[";
echo minSwaps($s2); // Output: 2
$s3 = "[]";
echo minSwaps($s3); // Output: 0
?> Explanation:
Time Complexity:
This solution ensures that we meet the constraints, even for large inputs. |
Beta Was this translation helpful? Give feedback.
We can use a two-pointers approach, which is efficient given the constraints.
Approach:
Track Balance: As we iterate through the string, we can track the balance between opening and closing brackets:
'['
.']'
.Identify Imbalance: When the balance becomes negative, it indicates that there are more closing brackets
']'
than opening brackets'['
at that point in the string. This is where we need to swap brackets to make the string balanced.Count Swaps: To correct an imbalance:
max_imbalance
to track the maximum imbalance observed during the iteration.