LeetCode: Minimum Number of Swaps to Make the String Balanced
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
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 s balanced.
?
Example 1:
Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]".
Example 2:
领英推荐
Input: s = "]]][[["
Output: 2
Explanation: You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "[]][][".
- Swap index 1 with index 5. s = "[[][]]".
The resulting string is "[[][]]".
Solution:
Approach:
Complexity:
Variable Description:
import math
class Solution:
def minSwaps(self, string: str) -> int:
stack = []
invalid = 0
for s in string:
if not stack and s == "]":
invalid += 1
elif stack and s == "]":
stack.pop()
else:
stack.append(s)
return math.ceil(invalid / 2)
??? Uncover a secret LeetCode trick in the comments! ????
Student at Dr. A.P.J. Abdul Kalam Technical University
4 个月class Solution: ??def minSwaps(self, string: str) -> int: ????# ??? Secret LeetCode Trick:? ????# Instead of importing 'math' and using 'math.ceil' (which could add extra overhead),? ????# we can cleverly use the formula '- (invalid // -2)' to get the ceiling of 'invalid / 2'.? ????# ?? Additionally, we optimize space by using an integer 'stack' to track unmatched '['? ????# rather than a list. This reduces space complexity from O(n) to O(1)? ????# and speeds up the operations, as integer arithmetic is faster than list operations like append() and pop(). ????? ????stack = 0?# Tracks the net count of unmatched opening brackets '[' ????invalid = 0?# Tracks the number of unmatched closing brackets ']' ????? ????for s in string: ??????if not stack and s == "]": ????????invalid += 1?# Unmatched closing bracket ??????elif stack and s == "]": ????????stack -= 1?# Match with a previous opening bracket ??????else: ????????stack += 1?# Unmatched opening bracket ????? ????return - (invalid // -2)?# Calculate the ceiling of invalid / 2