Skip to content
Decoder

Minimum Remove to Make Valid Parentheses

Medium

Problem

You get a string s of lowercase letters and the brackets ( and ). Remove the minimum number of brackets (from any positions) so that the brackets left are balanced and properly nested, and return the resulting string. Letters always stay, and the remaining characters keep their order.

Several answers may be equally short. Return any valid answer: the tests check that your string is balanced, that it is s with only brackets removed, and that it is as long as possible.

Example 1

Input
s = "lee(t(c)o)de)"
Output
"lee(t(c)o)de"
Why
"lee(t(co)de)" is also fine

Example 2

Input
s = "a)b(c)d"
Output
"ab(c)d"

Example 3

Input
s = "))(("
Output
""

Constraints

  • 1 <= s.length <= 10^5
  • Each s[i] is (, ), or a lowercase English letter.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.