Balance Mixed Bracket Types with Minimum Deletions
Dynamic ProgrammingModel answerLast updated
Delete the fewest bracket characters to make all remaining brackets properly matched and nested, keeping all non-bracket characters intact.
You're given a string s containing letters and three types of brackets: (), [], and {}. Your task is to delete the minimum number of bracket characters so that all remaining brackets are properly matched and nested.
Requirements:
- Each opening bracket must match with the correct closing bracket type:
(with),[with],{with} - Brackets must be properly nested—no crossing pairs (for example,
([)]is invalid because the pairs cross) - All non-bracket characters must remain in their original positions
- Return any valid solution if multiple optimal answers exist
Example:
Input: "([{ab)"
Output: "(ab)"
Explanation: Removing [ and { leaves (ab), where the parentheses are properly matched. All letters remain in place.
Constraints:
- String length ≤ 5000
- Input contains only letters (a-z, A-Z) and bracket characters from
()[]{}.
Hints
Hint 1
Greedy approaches fail with mixed bracket types—consider what happens with input like '[(]' versus '[()]'
Hint 2
This is about finding the longest valid bracket subsequence, not just counting mismatches
Hint 3
Interval DP works well: think about pairing the first bracket with a matching bracket later in the sequence
Hint 4
The recurrence has two cases: either skip the first bracket, or pair it with a matching bracket at position k
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why Greedy Fails
With only one bracket type, a simple stack suffices: match each closer with the nearest opener and discard extras. With mixed types, this breaks down. Consider [(]:
- Greedy "discard mismatched closers" keeps nothing
- Optimal solution keeps
[](delete the middle()
Or [(])]:
- One greedy heuristic keeps
[](2 brackets) - Optimal keeps
[()](4 brackets)
Local decisions change which future pairs can nest, so we need dynamic programming.
Core Insight
Removing minimum brackets = keeping maximum valid brackets. Since letters never affect validity, we keep all letters and run DP only on bracket positions.
Extract brackets into array b. Define dp[i][j] = maximum brackets we can keep from range b[i:j] that form a valid sequence.
For the first bracket b[i], we have two options:
- Skip it: inherit
dp[i+1][j] - Pair it with some
b[k]wherei < k < j: ifb[i]is an opener andb[k]is its matching closer, we get2 + dp[i+1][k] + dp[k+1][j]
The pairing works because proper nesting guarantees the region inside [i, k] and the region after k are independent subproblems.
Take the maximum across both options. Base case: dp[i][i] = 0.
Why This Works
Every valid bracket sequence either:
- Is empty, or
- Starts with an opener that pairs with some closer at position
k, with valid sequences inside and after the pair
Proper nesting ensures these regions don't overlap. The recurrence explores all possible pairings, enforces type matching (only pair b[i] with the correct closing bracket), and solves each subproblem optimally.
Reconstruction
After computing dp[0][m], trace back through decisions to identify which bracket positions are kept. Use a stack to avoid deep recursion:
- If
dp[i][j] == dp[i+1][j], bracketiwas skipped - Otherwise, find the
kwhere pairing occurred, mark positionsiandkas kept, and push both subproblems onto the stack
Build output by including all letters plus kept bracket positions.
Complexity
- Time: O(m³) where m is the number of brackets. We have O(m²) states and scan for partner
kin each, though only matching pairs do real work - Space: O(m²) for the DP table, O(n) for output
In practice, m is much smaller than n (total string length), and the constant factor is low since most positions skip the inner loop.
Implementation
def balance_mixed_brackets(s: str) -> str:
openers = {'(': ')', '[': ']', '{': '}'}
closers = set(openers.values())
# Extract bracket positions and characters
positions = [i for i, ch in enumerate(s) if ch in openers or ch in closers]
brackets = [s[i] for i in positions]
m = len(brackets)
# DP table: dp[i][j] = max valid brackets in brackets[i:j]
dp = [[0] * (m + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
current_row = dp[i]
next_row = dp[i + 1]
ch = brackets[i]
matching_closer = openers.get(ch) # None if ch is a closer
for j in range(i + 1, m + 1):
# Option 1: skip brackets[i]
best = next_row[j]
# Option 2: pair brackets[i] with brackets[k]
if matching_closer is not None:
for k in range(i + 1, j):
if brackets[k] == matching_closer:
candidate = 2 + next_row[k] + dp[k + 1][j]
best = max(best, candidate)
current_row[j] = best
# Reconstruct kept bracket positions
kept = set()
stack = [(0, m)]
while stack:
i, j = stack.pop()
if i >= j:
continue
# Was brackets[i] skipped?
if dp[i][j] == dp[i + 1][j]:
stack.append((i + 1, j))
continue
# Find the pairing position k
matching_closer = openers[brackets[i]]
for k in range(i + 1, j):
if brackets[k] == matching_closer:
if dp[i][j] == 2 + dp[i + 1][k] + dp[k + 1][j]:
kept.add(positions[i])
kept.add(positions[k])
stack.append((i + 1, k))
stack.append((k + 1, j))
break
# Build result: all letters + kept brackets
all_brackets = set(openers) | closers
return ''.join(ch for idx, ch in enumerate(s)
if ch not in all_brackets or idx in kept)
Edge Cases
- Empty string or no brackets: return unchanged
- Only openers or only closers: delete all brackets, keep letters
- Crossing patterns like
([)]: one pair survives (either()or[]) - Deep nesting: iterative reconstruction avoids stack overflow
- Ties between equally good solutions: the code prefers skipping when tie occurs
Example Walkthrough
For s = "([{ab)":
- Brackets:
['(', '[', '{', ')']at positions[0, 1, 2, 5] brackets[0] = '('can pair withbrackets[3] = ')'- Value:
2 + dp[1][3] + dp[4][4] dp[1][3]covers[{which have no matching pairs → 0- Total: 2 brackets kept
- Reconstruction marks positions 0 and 5
- Output:
(ab)
Key Interview Signals
- Recognizing greedy failure: Show a counterexample early
- Problem reformulation: "Minimum deletions" becomes "maximum valid subsequence"
- Structural recurrence: First bracket either skips or pairs with a matching bracket, splitting into independent subproblems
- Accurate complexity: State O(m³) time honestly, noting m is bracket count not full string length
- Bug-free reconstruction: Handle half-open ranges correctly when building the output string