#1249

Minimum Remove to Make Valid Parentheses

Medium
StringStackTwo PointersStack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a two-pass approach to count and remove invalid parentheses. This is efficient because it only requires a single scan to count and another to build the valid string.

⚙️

Algorithm

2 steps
  1. 1Step 1: Count the number of unmatched '(' and ')' in the string.
  2. 2Step 2: Create a new string, adding characters only if they are valid (i.e., not exceeding the counts of '(' and ')').
solution.py22 lines
1def minRemoveToMakeValid(s):
2    open_count = 0
3    for char in s:
4        if char == '(': open_count += 1
5        elif char == ')':
6            if open_count > 0: open_count -= 1
7    close_count = 0
8    for char in s:
9        if char == ')': close_count += 1
10    result = []
11    for char in s:
12        if char == '(':
13            if open_count > 0:
14                result.append(char)
15                open_count -= 1
16        elif char == ')':
17            if close_count > 0:
18                result.append(char)
19                close_count -= 1
20        else:
21            result.append(char)
22    return ''.join(result)

Complexity note: The time complexity is O(n) because we traverse the string a constant number of times, and the space complexity is O(n) for storing the result.

  • 1Valid parentheses must have matching pairs.
  • 2Counting unmatched parentheses helps in constructing the valid string.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.