Skip to main content

Minimum Remove to Make Valid Parentheses - Solution & Explanation

MediumStringStack16 min readAsked at: Amazon, Microsoft, Apple +8
Practice this problem

Problem Statement

Given a string s of '(' , ')' and lowercase English characters.

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, contains only lowercase characters, or
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • It can be written as (A), where A is a valid string.

 

Example 1:

Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

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

Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

 

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either '(' , ')', or lowercase English letter.

Approach Overview

Problem Overview: You receive a string containing lowercase letters and parentheses. The goal is to remove the minimum number of characters so the remaining parentheses form a valid expression. A valid string means every opening ( has a matching closing ) in the correct order.

Approach 1: Two-Pass String Traversal with Index Tracking (Time: O(n), Space: O(n))

This method scans the string twice to filter invalid parentheses. During the first pass, iterate left to right and track the balance of open parentheses. Append characters to a temporary result but skip any closing parenthesis ) that does not have a matching open. This guarantees that the intermediate string never has excess closing brackets.

The second pass runs right to left to remove extra opening parentheses. Track remaining unmatched ( and skip them when building the final string. Using two passes ensures both imbalance cases are handled cleanly without complex bookkeeping. This approach relies purely on string traversal and counters, making it easy to implement when working with string processing problems.

Approach 2: Single-Pass Efficient Stack Solution (Time: O(n), Space: O(n))

The stack-based method records indices of unmatched parentheses while iterating once through the string. Push the index of every ( onto a stack. When encountering ), check the stack: if an opening parenthesis exists, pop it to form a valid pair; otherwise record the index of the invalid closing parenthesis.

After traversal, any remaining indices in the stack correspond to unmatched opening parentheses. Combine these with invalid closing indices and remove those positions from the string. The final string contains only valid pairs. This approach is common in parentheses validation problems because the stack directly models the nesting structure of expressions.

Recommended for interviews: The single-pass stack approach is the one most interviewers expect. It demonstrates clear understanding of parenthesis matching using a LIFO structure and maintains linear time complexity. The two-pass traversal is also strong because it avoids extra index bookkeeping and shows clean reasoning about invalid cases. Mentioning both approaches shows depth: one focuses on stack mechanics, the other on careful string filtering.

Approach 1: Two-Pass String Traversal with Index Tracking

This approach involves performing two passes over the string. In the first pass, traverse the string to identify unmatched closing parentheses and their indices. In the second pass, traverse from right to left to identify unmatched opening parentheses. This process allows removing these indices to yield a balanced parentheses string.

An array is used to filter out invalid closing parentheses on the first pass. The second pass corrects the string from the right by ignoring invalid opening parens, then reverses the string to final form.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string, since each character is visited once in each pass.
Space Complexity: O(n), as we potentially have to store the valid portion of the string.

Try this approach in the editor →

Approach 2: Single-Pass Efficient Stack Solution

This strategy employs a single-pass solution with a stack to track the indices of unmatched parentheses. Upon completing the pass, these tracked indices inform which characters can remain in the final valid string output. This approach saves memory by avoiding additional passes over the string.

The C implementation uses an integer stack to track the positions of parentheses. It marks invalid parentheses with a dot character and subsequently uses a secondary pass to construct the valid string.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), since each position in the strings is evaluated at most twice.
Space Complexity: O(n) for the indices stored during parentheses checking.

Try this approach in the editor →

Approach 3: Two Passes

First, we scan from left to right and remove the extra right parentheses. Then, we scan from right to left and remove the extra left parentheses.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the string s.

Similar problems:

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Two-Pass String Traversal with Index Tracking

Time Complexity: O(n), where n is the length of the string, since each character is visited once in each pass.
Space Complexity: O(n), as we potentially have to store the valid portion of the string.

Single-Pass Efficient Stack Solution

Time Complexity: O(n), since each position in the strings is evaluated at most twice.
Space Complexity: O(n) for the indices stored during parentheses checking.

Two Passes—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Two-Pass String Traversal with Index TrackingO(n)O(n)When you prefer simple logic using counters and sequential scans without managing a stack
Single-Pass Efficient Stack SolutionO(n)O(n)Best general approach for parenthesis validation and matching problems

Video Solution

Minimum Remove to Make Valid Parentheses - Leetcode 1249 - Python • NeetCodeIO • 36,334 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Remove to Make Valid Parentheses easy or hard?
The problem is rated Medium because it combines string processing with stack logic. The algorithm itself is linear, but handling invalid indices and reconstructing the string correctly requires careful implementation.
Minimum Remove to Make Valid Parentheses Python/Java solution
Python and Java implementations typically follow the stack approach. Iterate through the string, push indices of '(' onto the stack, and track unmatched ')'. After the pass, remove all invalid indices and rebuild the string. Both languages achieve O(n) time and O(n) space complexity.
How to solve Minimum Remove to Make Valid Parentheses in O(n)?
Traverse the string while tracking unmatched parentheses. With the stack method, push indices of '(' and remove invalid ')'. After traversal, remove any remaining indices stored in the stack. Another O(n) approach performs two passes: first remove extra closing parentheses, then remove extra opening ones.
What is the best approach for Minimum Remove to Make Valid Parentheses?
The most common solution uses a stack to track indices of unmatched parentheses while scanning the string once. Each '(' index is pushed onto the stack, and matching ')' pops it. Any remaining indices represent invalid characters that should be removed. This method runs in O(n) time with O(n) space.
Is Minimum Remove to Make Valid Parentheses asked at Google/Amazon/Meta?
Parentheses validation and expression-cleaning problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants include Valid Parentheses, Remove Invalid Parentheses, and Minimum Remove to Make Valid Parentheses, all testing stack usage and string traversal skills.
What data structure is used in Minimum Remove to Make Valid Parentheses?
A stack is the primary data structure because it naturally models nested parentheses. It stores indices of opening brackets and allows constant-time matching when a closing bracket appears. Some solutions also use arrays or sets to mark invalid indices before rebuilding the string.
What is the time complexity of Minimum Remove to Make Valid Parentheses?
Optimal solutions run in O(n) time because the string is processed with a single or double linear scan. Each character is visited at most twice. Space complexity is O(n) when storing indices of invalid parentheses or building the result string.

Ready to solve this problem?

Practice Minimum Remove to Make Valid Parentheses with our built-in code editor and test cases.

Practice on FleetCode