KatInterview

Trim a Bracket String to Its Longest Balanced Form

Stacks & QueuesAuto-graded · 28 test cases
MediumAuto-gradedStacks & Queuesstacksstringsgreedy

Last 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 s is 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.