Problem 1249

Abstract / Summary

Remove the fewest parentheses to make the input string valid without changing the order of remaining characters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1249.py

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        # emit at most as many "one" as "two"
        def filter(s, one, two):
            have = 0
            for c in s:
                if   c == one:
                    have += 1
                elif c == two:
                    if have == 0:
                        continue # skip
                    have -= 1

                yield c

        open  = filter(s,                    "(", ")") # left-to-right "()"
        close = filter(reversed(list(open)), ")", "(") # right-to-left ")("

        return "".join(reversed(list(close)))
19 lines | 631 bytes | submitted April 1, 2024 | GitHub   26% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (1+ million submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a method minRemoveToMakeValid that receives a string s and returns a new string where the minimum number of parentheses have been removed to make the parentheses balanced. The algorithm works in two passes: a left-to-right pass that discards unmatched closing parentheses, followed by a right-to-left pass that discards unmatched opening parentheses. The result is assembled by reversing the intermediate generators appropriately.

Core Logic

The heart of the solution is the nested filter generator. It receives a source iterable s and two characters, one and two, representing the opening and closing symbols for the current pass. A counter have tracks how many opening symbols have been seen but not yet matched.

def filter(s, one, two):
    have = 0
    for c in s:
        if   c == one:
            have += 1
        elif c == two:
            if have == 0:
                continue # skip
            have -= 1
        yield c

During the first invocation, filter is called with "(" as one and ")" as two. As the generator iterates over the original string, each opening parenthesis increments have. When a closing parenthesis appears, the generator checks whether there is a pending opening parenthesis (have > 0). If not, the closing parenthesis is omitted (continue). Otherwise, the counter is decremented and the character is yielded. This pass guarantees that no closing parenthesis appears without a matching opening one to its left.

The result of the first pass is stored in the variable open. Because filter returns a generator, the code materializes it into a list before reversing:

open = filter(s, "(", ")")          # left-to-right "()"

The second pass processes the characters in reverse order, swapping the roles of opening and closing symbols. By feeding reversed(list(open)) into filter with ")" as one and "(" as two, the generator now removes any unmatched opening parentheses that remain after the first pass.

close = filter(reversed(list(open)), ")", "(")  # right-to-left ")("

Finally, the characters produced by the second pass are reversed again to restore the original order, and concatenated into the output string:

return "".join(reversed(list(close)))

Edge Cases Handled

The algorithm gracefully handles strings that contain no parentheses at all. Since the filter generator yields every character unchanged when it does not match either one or two, the original string is returned unchanged.

When the input consists solely of opening parentheses, the first pass leaves all characters untouched because there are no closing symbols to trigger the skip logic. The second pass then removes each opening parenthesis because the reverse traversal finds no matching closing counterpart, resulting in an empty string.

Conversely, a string composed only of closing parentheses is cleaned entirely during the first pass. Each closing parenthesis encounters have == 0 and is therefore skipped, yielding an empty intermediate sequence that propagates through the second pass unchanged.

Strings with interleaved non-parenthesis characters (letters, digits, spaces, etc.) are preserved because the generator yields any character that does not equal one or two without affecting the counter. This ensures that the relative order of non-parenthesis characters remains intact while only the parentheses are examined for balance.

Nested parentheses are correctly processed because the counter have reflects the depth of nesting. Each opening parenthesis increments the counter, and each matching closing parenthesis decrements it, allowing the algorithm to keep track of multiple levels without additional data structures.

Performance Optimizations

The solution leverages generator functions to avoid constructing intermediate strings during each pass. By yielding characters on the fly, memory consumption is limited to the size of the final list conversions required for reversal. The use of list(open) and list(close) is confined to the two reversal steps; no full copies of the string are created beyond these points.

Reversing the sequence only twice-once before the second pass and once after-keeps the number of traversals minimal. The first pass processes the input in linear order, the second pass processes the already filtered characters in reverse order, and the final reversal restores the original orientation. This three-step traversal pattern ensures that each character is examined a constant number of times.

The counter have is a simple integer variable, providing O(1) updates for each character. The conditional checks (c == one, c == two) are inexpensive and avoid the overhead of more complex data structures such as stacks or hash tables.

By structuring the algorithm around pure functional transformations (filtering and reversing) rather than mutable state, the code benefits from Python’s efficient iterator protocol, which contributes to both speed and low memory overhead for large input strings.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a box filled with little plastic parentheses that look like tiny curved mouths. Some mouths open to the left and some open to the right. To make a happy pattern, every mouth that opens must have a matching mouth that closes, and they have to be in the right order.

The code is like a clever helper that walks along the row of parentheses to check each one. If it sees an opening mouth, it remembers it. If it sees a closing mouth, it checks if there is already an opening one waiting to be paired up. If there is no open mouth waiting, the closing one is not allowed to stay, so the helper skips that one and leaves it behind.

After checking from the left side, the helper does the exact same thing again but starts from the other side, looking at the row backward. This ensures that any extra opening mouths that never found a partner get left behind too. By the time the helper finishes both walks, every remaining parentheses is part of a perfect, matched pair. Everything that was left over and caused trouble has been taken out, leaving behind a clean and tidy string.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.41 | σ = 1.55

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
33 links | 20 authors | 9 languages

Videos

12 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   April 1, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality