Minimum Remove to Make Valid Parentheses

Given a string s made of '(', ')' and lowercase English letters, remove the minimum number of parentheses (at any positions) so that the resulting string is valid, and return it. A string is valid if it is empty or contains only lowercase letters, or it can be written as AB where A and B are valid, or as (A) where A is valid.

30:00

Minimum Remove to Make Valid Parentheses
medium
Free written solution
Topics
Companies

Given a string s made of '(', ')' and lowercase English letters, remove the minimum number of parentheses (at any positions) so that the resulting string is valid, and return it.

A string is valid if it is empty or contains only lowercase letters, or it can be written as AB where A and B are valid, or as (A) where A is valid.

Example 1:
Input: {"s":"lee(t(c)o)de)"}
Output: lee(t(c)o)de
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

  • s[i]s[i] is either '(', ')', or a lowercase English letter.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"lee(t(c)o)de)"}

Scan the 13 characters left to right. The stack will hold the index of every '(' still waiting for its partner.

Scan left to right

waiting (

matched pair

removed

l

0

e

1

e

2

(

3

t

4

(

5

c

6

)

7

o

8

)

9

d

10

e

11

)

12

Stack of open '(' indices

empty

removed

0

open waiting

0

Variables
VariableValue
n13
stack[]
removed0
DepthFunction Call
Stack empty
0/12