KatInterview

Balance Mixed Bracket Types with Minimum Deletions

Dynamic ProgrammingModel answer
HardModel answerDynamic Programmingdynamic-programmingstringsinterval-dp

Last 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