NeetCode #116LC-1963MediumArrays & Hashing
← Back to All Problems#116 · #1963 · Minimum Number of Swaps to Make the String Balanced(使字符串平衡的最少交换次数)
📌 Problem Statement & Constraints
Given a 0-indexed string
s of even length consisting of [ and ], return the minimum number of swaps (of any two indices) needed to make it balanced. Constraints: 1 <= s.length <= 10^5.💡 Core Algorithmic Approaches
- Scan the string tracking the running balance:
[adds 1,]subtracts 1. - Record the deepest negative dip -- that is, the largest deficit of opening brackets encountered so far.
- Each swap can fix exactly two unmatched brackets (one misplaced
]and one misplaced[), so the answer isceil(max_deficit / 2). - Equivalently, count the maximum nesting depth of unmatched closing brackets and halve it, rounding up.
💻 Benchmark Python3 Implementation
class Solution:
def minSwaps(self, s: str) -> int:
depth = 0
max_deficit = 0
for ch in s:
if ch == "[":
depth += 1
else:
depth -= 1
max_deficit = max(max_deficit, -depth) # deepest unmatched ']' deficit
return (max_deficit + 1) // 2 # each swap fixes two brackets⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two counters.
⚠️ Interview Pitfalls & Follow-ups
- Using a stack and counting unmatched brackets, then dividing by 2 with truncation: the count of unmatched
]is exactly the max deficit, and the halving must round up. - Returning
max_deficit: each swap fixes one]and one[, so the answer is half. - Simulating actual swaps: unnecessary and error-prone; the deficit bound is exact.
- Ignoring the guaranteed even length: it ensures the string can always be balanced.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
使字符串平衡的最少交换次数
给你一个字符串 s,下标从 0 开始,且长度为 偶数 n。字符串恰有 n / 2 个开括号 [ 和 n / 2 个闭括号 ] 。如果一个字符串满足以下条件,则称其为 平衡字符串 :① 每一个开括号 [ 都有一个在它右侧的闭括号 ] 与之匹配;② 每一个闭括号 ] 都有一个在它左侧的开括号 [ 与之匹配。你可以交换任意两个下标的字符。返回使 s 变成平衡字符串所需的 最少 交换次数。约束:1 ≤ s.length ≤ 10^6;s.length 为偶数;s 仅含 [ 和 ] 。
核心要点
- 贪心:统计最大未匹配深度(标准解) :遍历字符串,用 bal 维护当前平衡度( [ 加一、 ] 减一),用 unmatched 记录 bal 的历史最小值。
- 为什么 -unmatched 就是未匹配的闭括号数 : bal 的最小值(取负)恰好等于「前缀中多出来的闭括号数」,也就是必须被交换掉的闭括号个数。
- 每次交换修复两个 :一次交换可以把一个多余的闭括号和一个多余的开括号互换位置,从而修复两个未匹配项,因此答案为 ceil(unmatched / 2) 。
- 公式 (-unmatched + 1) // 2 :即向上取整除法。
常见陷阱
- 用栈模拟配对再计数 :虽然可行(栈的大小即为未匹配数),但会占用 O(n) 空间;用平衡度最小值可做到 O(1)。
- 忘记向上取整 :未匹配数为奇数时, unmatched / 2 会丢失 0.5,必须用 (x + 1) // 2 或 math.ceil 。
- 把答案写成 -unmatched :那是未匹配的 字符数 ,不是交换次数。一次交换修复两个字符,因此要除以 2 并向上取整。
- 误以为需要真正执行交换 :题目只问最少次数,用计数公式即可,无需模拟。
参考实现
class Solution:
def minSwaps(self, s: str) -> int:
bal = 0
unmatched = 0
for c in s:
bal += 1 if c == '[' else -1
unmatched = min(unmatched, bal) # bal 的历史最小值(负值)
# -unmatched = 未匹配的闭括号数;一次交换修复两个
return (-unmatched + 1) // 2