Trim a Bracket String to Its Longest Balanced Form
Stacks & QueuesAuto-graded · 28 test casesLast updated
Tests stack-based bracket matching: find and remove the fewest characters from a parentheses-only string to leave a fully balanced result.
You have a string s made up entirely of '(' and ')' characters. Your task is to remove as few characters as possible so that what remains is balanced, and return that resulting string.
A balanced string is one where every opening bracket is eventually closed by a matching closing bracket that appears later, every closing bracket has a corresponding opening bracket before it, and all pairs are properly nested. The empty string counts as balanced.
How the Matching Rule Works
When multiple ways to remove the minimum number of characters exist, the answer is uniquely determined by the following rule:
Process the string from left to right. Each time you encounter a ')', pair it with the most recent '(' that has not yet been matched. If no unmatched '(' exists at that point, this ')' has no partner. Any '(' still without a partner after you reach the end of the string also has no partner. Remove exactly the characters that were never matched — no more, no less.
Constraints
0 <= len(s) <= 10^5- Every character in
sis either'('or')'
Examples
Example 1
Input: trim_brackets('()())')
Output: '()()'
Example 2
Input: trim_brackets('(()()')
Output: '()()'
Example 3
Input: trim_brackets('))((')
Output: ''
Hints
Hint 1
As you scan left to right, think about what information you need to remember in order to match each ')' with the right '(' later — specifically, which '(' characters are still waiting for a partner and where they sit in the string.
Hint 2
A stack that stores indices (not just a count) lets you record exactly which '(' characters end up unmatched, so you can mark them for removal. A plain counter tells you how many to remove but not which ones, which can produce the wrong output.
Hint 3
Two-phase approach: first pass marks unmatched ')' on the spot (empty stack when you hit one) and leaves unmatched '(' on the stack; second phase marks whatever indices remain on the stack. Then build the output by keeping every character that was not marked.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that "which characters are unmatched" is a more precise question than "how many characters are unmatched." Tracking indices on a stack answers both at once.
Single scan with a stack of indices
Walk through the string once, left to right:
- When you see a
'(', push its index onto the stack. It is waiting for a future')'. - When you see a
')'and the stack is non-empty, pop the top. That')'is now paired with the most recent waiting'(', exactly as the matching rule requires. - When you see a
')'and the stack is empty, no partner exists. Mark that index for removal immediately.
After the scan, every index still on the stack belongs to a '(' that never found a partner. Mark those for removal too.
Finally, build the output by joining all characters whose positions were not marked.
Why this is correct
The stack top always holds the index of the most recently seen unmatched '('. Popping on ')' therefore pairs it with the closest earlier unmatched opener — which is precisely what the problem's matching rule specifies. Storing indices rather than just a running count is what makes it possible to identify and remove exactly the right characters (not just the right number of them).
The pairs produced never overlap or cross, because anything pushed after index i is popped before index i can be. Non-crossing pairs where each opener precedes its closer form a properly nested, balanced string.
Minimality: every ')' removed had a strictly empty stack at the moment it was encountered, meaning closes had already outnumbered opens in that prefix — any balanced subsequence must discard at least that many closers. A symmetric suffix argument covers the unmatched openers. The algorithm removes exactly these two theoretical lower bounds.
Worked trace — s = "(()()"
| i | c | action | stack |
|---|---|---|---|
| 0 | ( | push 0 | [0] |
| 1 | ( | push 1 | [0, 1] |
| 2 | ) | pop 1 — paired | [0] |
| 3 | ( | push 3 | [0, 3] |
| 4 | ) | pop 3 — paired | [0] |
Index 0 remains on the stack and is marked for removal. Result: "()()".
Note: a counter-based approach would also delete one '(', but it might remove index 3 instead, returning "(())" — correct length, wrong string.
Complexity
- Time: O(n). Each character is visited once; each index is pushed and popped at most once; the final join is linear.
- Space: O(n) for the
keeparray, the stack (worst case all'('), and the output string.
Edge cases
- Empty string →
""(nothing to process). - All closers, e.g.
"))))"→ every closer hits an empty stack and is removed →"". - All openers, e.g.
"(((("→ all remain on the stack and are removed →"". - Already balanced → stack ends empty, nothing marked, original string returned.
from typing import List
def trim_brackets(s: str) -> str:
keep = [True] * len(s)
stack = [] # stores indices of unmatched '(' seen so far
for i, c in enumerate(s):
if c == '(':
stack.append(i)
elif stack:
stack.pop() # pair this ')' with the nearest unmatched '('
else:
keep[i] = False # ')' with no available partner — mark for removal
for i in stack:
keep[i] = False # leftover '(' that were never paired
return ''.join(c for c, k in zip(s, keep) if k)