FastPrepMinimum Remove to Make Valid Parentheses

Minimum Remove to Make Valid Parentheses

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given a string s containing ASCII letters, digits, opening parentheses, and closing parentheses, remove the minimum possible number of parentheses so that the remaining parentheses are balanced. You may not add or reorder characters.

Use this deterministic rule when several minimum-removal results are possible:

  1. Scan from left to right. Discard every closing parenthesis that has no unmatched opening parenthesis before it.
  2. After that scan, discard the still-unmatched opening parentheses from right to left.

Return the retained characters in their original relative order. Letters and digits are always retained.

Function

minRemoveToMakeValid(s: String) → String

Examples

Example 1

s = "lee(t(c)o)de)"return = "lee(t(c)o)de"

The final closing parenthesis has no matching opening parenthesis, so removing it produces a balanced result with one deletion.

Example 2

s = "a)b(c)d"return = "ab(c)d"

The closing parenthesis after a is unmatched during the left-to-right scan. Every other parenthesis can be retained.

Example 3

s = "))(("return = ""

Both closing parentheses are unmatched, and both opening parentheses remain unmatched, so all four are removed.

Constraints

  • 1 <= s.length <= 100000.
  • s contains only ASCII letters, digits, (, and ).

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String minRemoveToMakeValid(String s) {
    // Write your code here.
}
s"lee(t(c)o)de)"
expected"lee(t(c)o)de"
Checking account…