Balance Parentheses with Minimum Deletions

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement make_valid_parentheses_string(s), which takes a string s made up of lowercase ASCII letters ('a'–'z') together with opening and closing parentheses ('(' and ')'). Delete as few '(' and ')' characters as possible so that the remaining string has balanced parentheses.

A string has balanced parentheses when all of the following hold:

  • No lowercase letters are deleted or reordered, and surviving parentheses keep their original left-to-right relative positions.
  • Scanning from left to right, every ')' closes a prior '(' that has not already been closed (a running count of '(' minus ')' never becomes negative).
  • Every '(' is closed by the end of the string (the total count of '(' equals the total count of ')'). Strings with zero parentheses—including ""—are already balanced.

If more than one balanced string can be formed using the same minimum number of deletions, you may return any of them.

Examples

Example 1

Input:  s = "alg)o(ri(th)m)"
Output: "algo(ri(th)m)"

The ')' at index 3 appears before any '(', so it cannot be paired and must be deleted. The remaining parentheses at indices 5..13 ("(ri(th)m)") are already properly nested, yielding "algo(ri(th)m)" after 1 deletion.

Example 2

Input:  s = "(x(y)z"
Output: "x(y)z"

There are two '(' characters and only one ')', so at least 1 '(' must be deleted. Deleting the first '(' gives "x(y)z"; deleting the second '(' gives "(xy)z", which also uses 1 deletion and is an equally valid output.

Example 3

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

Every ')' precedes every '(', so no pair can ever match. All 6 parentheses must be deleted, leaving the empty string "".

Example 4

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

In the prefix "()())", three ')' characters appear against only two '(' characters, requiring 1 ')' deletion. In the suffix "(()", two '(' characters appear against one ')', requiring 1 '(' deletion. Deleting index 4 and index 5 leaves "()()()" using 2 deletions total.

Constraints

  • 0 <= len(s) <= 10^5
  • Every character in s is '(', ')', or a lowercase English letter ('a'–'z').

Step-by-step walkthrough

  1. Understand what makes a parentheses string valid

    We are given a string s made of lowercase letters, '(', and ')'. Letters must always stay in place, and we want to delete as few '(' and ')' characters as possible so the remaining string is valid.

    The easiest way to picture validity is a running balance as you read from left to right:

    • Start with balance = 0.
    • Add +1 at every '(', subtract -1 at every ')', and ignore letters.
    • The string is valid if balance never drops below 0 (every ')' has an earlier '(' to close) and ends at 0 (every '(' eventually gets closed).
    Valid:   "xy(z)w"     balance: 0, 0, +1, +1, 0, 0   (never < 0, ends at 0)
    Invalid: "x)y(z"      balance: 0, -1 ...            (drops below 0 at index 1!)
    Invalid: "(x(y)z"     balance: +1, +1, +2, +2, +1, +1 (ends at +1 instead of 0!)
    

    Multiple minimum-deletion answers can exist: in Example 2 ("(x(y)z"), deleting either '(' leaves a valid 5-character string ("x(y)z" or "(xy)z"). Pairing parentheses greedily from left to right matches the inner '(' at index 2 with ')' at index 4 and drops the leftover '(' at index 0, producing "x(y)z".

  2. Why brute force is too slow

    A brute-force search tries removing 0 parentheses, then every single parenthesis (1 removal), then every pair (2 removals), and stops as soon as a valid string appears. If s contains p parentheses, there are 2^p subsets in the worst case — at p = 30, 2^30 is already over a billion combinations, whereas s can have 100,000 characters.

    We only keep that subset search inside tests.py on tiny random strings (up to length 10) to cross-check our linear-time algorithm.

  3. Key idea: greedily pair each ')' with the nearest open '('

    Scan s once from left to right while maintaining a stack — a last-in, first-out list where append pushes a new item on top and pop removes the most recent item:

    1. When we see '(', push its index onto open_indices.
    2. When we see ')':
      • If open_indices is non-empty, pop the top index. That ')' and that '(' now form a valid matched pair, so we keep both.
      • If open_indices is empty, there is no free '(' anywhere to its left. This ')' can never be matched, so we record its index in indices_to_remove.
    3. After the scan finishes, any index still sitting in open_indices is an '(' that never found a ')' to its right. Record all of those in indices_to_remove too.

    Why is this guaranteed to delete the minimum possible number of parentheses?

    • Suppose the scan marks R unmatched ')' characters. When the R-th one is marked at index i, every '(' in s[0..i] has already been paired, meaning that prefix contains R more ')' than '('. Every valid output must delete at least R closers inside s[0..i].
    • Suppose m pairs matched and L openers remain on the stack. Then s has m + L openers and m + R closers. Since at least R closers must be deleted, at most m pairs can survive in any valid output, which forces at least L openers to be deleted as well.

    So no valid solution can delete fewer than R + L characters, and our greedy pass deletes exactly R + L while leaving m properly nested pairs.

  4. Phase 1: find every unmatched ')' and '(' index

    Notice a crucial detail: open_indices stores integer positions (like 3), not the character '('. All '(' characters look identical, so if we only pushed '(', we wouldn't know which '(' in s went unmatched when the loop ends!

    open_indices: List[int] = []
    indices_to_remove: Set[int] = set()
    
    for i, ch in enumerate(s):
        if ch == "(":
            open_indices.append(i)
        elif ch == ")":
            if open_indices:
                open_indices.pop()
            else:
                indices_to_remove.add(i)
    
    # Any '(' index still on the stack never found a matching ')' to its right.
    for index in open_indices:
        indices_to_remove.add(index)
    
  5. Phase 2: rebuild the string in one O(n) pass

    Python strings are immutable (unchangeable in place once created, so every edit allocates a brand-new string). Deleting characters one at a time with s = s[:i] + s[i + 1:] copies up to n characters on every deletion and degrades to O(n^2) time on inputs like ")))))...".

    Instead, we test i not in indices_to_remove in O(1) average time per character, collect surviving characters in a Python list, and call "".join(kept_chars) once at the end in O(n) time:

    kept_chars: List[str] = []
    for i, ch in enumerate(s):
        if i not in indices_to_remove:
            kept_chars.append(ch)
    
    valid_string = "".join(kept_chars)
    
  6. Trace Example 4 and Example 1 with a pointer diagram

    Let's trace Example 4, s = "()())(()" (indices 0..7):

    Index:   0    1    2    3    4    5    6    7
    Char:    (    )    (    )    )    (    (    )
    
    i = 0, '(' -> push 0               | open_indices = [0]    | indices_to_remove = {}
    i = 1, ')' -> pop 0 (paired 0 & 1) | open_indices = []     | indices_to_remove = {}
    i = 2, '(' -> push 2               | open_indices = [2]    | indices_to_remove = {}
    i = 3, ')' -> pop 2 (paired 2 & 3) | open_indices = []     | indices_to_remove = {}
    i = 4, ')' -> stack empty! mark 4  | open_indices = []     | indices_to_remove = {4}
    i = 5, '(' -> push 5               | open_indices = [5]    | indices_to_remove = {4}
    i = 6, '(' -> push 6               | open_indices = [5, 6] | indices_to_remove = {4}
    i = 7, ')' -> pop 6 (paired 6 & 7) | open_indices = [5]    | indices_to_remove = {4}
    
    End of loop -> flush open_indices  | open_indices = [5]    | indices_to_remove = {4, 5}
    
    Keep indices not in {4, 5}:
      s[0..3]="()()", [skip 4], [skip 5], s[6..7]="()"  -->  "()()()"
    

    And Example 1, s = "alg)o(ri(th)m)":

    • i = 0..2 ("alg"): letters, ignored by the stack.
    • i = 3 (')'): open_indices is empty -> indices_to_remove.add(3).
    • i = 5 ('(') and i = 8 ('('): open_indices becomes [5, 8].
    • i = 11 (')') pops 8, and i = 13 (')') pops 5 -> both nested pairs match!
    • End of loop: open_indices is empty, so only index 3 is omitted, producing "algo(ri(th)m)".
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def make_valid_parentheses_string(s: str) -> str:
        # open_indices: stack of int positions where unmatched '(' appeared, e.g. [3, 5]
        open_indices: List[int] = []
        # indices_to_remove: set of int positions of unmatched '(' or ')' to omit from output
        indices_to_remove: Set[int] = set()
    
        # Phase 1: Scan left to right, pairing each ')' with the nearest unmatched '(' before it.
        for i, ch in enumerate(s):
            if ch == "(":
                open_indices.append(i)
            elif ch == ")":
                if open_indices:
                    # Pair this ')' with the most recently opened '(' so both stay in the output.
                    open_indices.pop()
                else:
                    # No unmatched '(' exists to the left, so this ')' can never be balanced.
                    indices_to_remove.add(i)
    
        # Phase 2: Any '(' index still on the stack never found a matching ')' to its right.
        for index in open_indices:
            indices_to_remove.add(index)
    
        # Phase 3: Rebuild the string in one O(n) pass instead of O(n^2) repeated string slicing.
        kept_chars: List[str] = []
        for i, ch in enumerate(s):
            if i not in indices_to_remove:
                kept_chars.append(ch)
    
        return "".join(kept_chars)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine reading an expression from left to right and placing a numbered sticky note onto a stack (a last-in, first-out pile where you always add and remove from the top) every time you see an opening '('. Whenever a closing ')' arrives, it peels the top sticky note off the pile to complete a pair. If a ')' arrives when the pile is completely empty, no earlier '(' is available to match it, so that ')' is a broken closer and must be crossed out; when you reach the end of the string, any sticky notes still sitting on the pile are unclosed '(' characters that must be crossed out too.

A naive brute-force approach tries deleting all subsets of 1, 2, ... parentheses until a valid string appears, which takes O(2^n) time and stalls past ~30 parentheses. Simply counting total '(' and total ')' also fails because order matters: ")(" has one of each, yet neither parenthesis has a partner on the right side of it.

Walk through "(x(y)z" (Example 2, length 6) to see the passes in action:

  1. i = 0 ('('): push 0 onto the stack (open_indices = [0], indices_to_remove = {}).
  2. i = 1 ('x'): letter, leave alone.
  3. i = 2 ('('): push 2 onto the stack (open_indices = [0, 2]).
  4. i = 3 ('y'): letter, leave alone.
  5. i = 4 (')'): stack is non-empty, so pop 2 (open_indices = [0]), pairing indices 2 and 4; i = 5 ('z') is left alone. After the loop, 0 remains on open_indices, so add 0 to indices_to_remove = {0} and join all unmarked characters to return "x(y)z".

Complexity

Let n be the length of s.

  • Time: O(n). We scan the n characters once to match parentheses (pushing and popping each index at most once in O(1) time), copy up to n leftover stack indices into indices_to_remove, and scan s one more time with O(1) average-time set lookups before a single O(n) "".join(...).
  • Space: O(n). In the worst case (such as "(((..." or ")))..."), open_indices, indices_to_remove, and kept_chars each hold up to n items.

Edge cases

  • Empty string or letters only ("", "abc"): Both open_indices and indices_to_remove stay empty, returning the input unchanged.
  • Already valid string ("(a(b)c)()"): Every '(' is popped by a ')', zero removals occur, and the exact original string is returned.
  • All parentheses invalid (")))(((", "))a(("): Every ')' before '(' hits an empty stack and every trailing '(' stays on the stack, leaving "" and "a".
  • Equal counts in invalid order ("()())(()"): Contains four '(' and four ')', yet the ')' at index 4 and '(' at index 5 go unmatched, returning "()()()".
  • Multiple valid optimal answers ("(x(y)z"): Either '(' can be removed ("x(y)z" or "(xy)z"); our stack leaves the unclosed '(' on the bottom (0) after index 2 pairs with index 4, returning "x(y)z".
  • Deep nesting (50,000 nested '('): Iterative loops with an explicit list avoid Python's ~1,000-frame call-stack recursion limit.

Common mistakes

  • Deleting letters: Letters never affect parenthesis balance and must always remain in their original relative order.
  • Forgetting unclosed '(' left on the stack: Only dropping unmatched ')' turns "()())(()" into "()()(()", which is still invalid.
  • Pushing '(' characters instead of integer indices: At the end of the scan, knowing how many '(' went unmatched is not enough to rebuild the string in one pass unless you know which indices to skip (or run a second reverse pass).
  • Repeated string slicing (s = s[:i] + s[i+1:]): Each slice copies up to n characters, turning O(n) deletions into O(n^2) total time.

Alternative approaches

  • Two passes with an integer counter (no index stack or removal set): Pass 1 scans left to right with an open_count integer, skipping any ')' that arrives when open_count == 0. At the end of Pass 1, open_count equals the number of extra '(' characters. Pass 2 scans the surviving list right to left and drops the first open_count '(' characters it sees (the rightmost ones), then reverses the list. Both time and space remain O(n) in Python because strings are immutable (unchangeable in place once created, so building a modified string requires a separate character buffer).

Follow-up questions

  • How would your solution change if you only needed to compute the minimum deletion count instead of building the valid string? Replace the stack and set with two integers, open_count = 0 and unmatched_close = 0. Increment open_count on '('; on ')', decrement open_count if open_count > 0, otherwise increment unmatched_close. Returning unmatched_close + open_count runs in O(n) time and O(1) extra space because we never construct the edited string.
  • When several minimum-deletion strings are valid, how could you guarantee returning the alphabetically (lexicographically) first one? Lexicographical order is dictionary order comparing character codes from left to right, where in ASCII '(' < ')' < 'a'..'z'. First count close_budget (the R excess ')') and open_budget (the L excess '('). In a left-to-right pass, whenever '(' arrives right after kept ')' characters and we still have unused close_budget, pop those ')' so the smaller '(' moves into the earlier slot (for example, turning "(a)(b))" into "(a(b))" rather than "(a)(b)"); finally, drop the last L '(' characters in a reverse pass so earlier '(' characters stay ahead of larger letters.
  • Is it possible to achieve O(1) auxiliary memory, and how does string mutability in the host language affect that bound? Eliminating the index stack and hash set via the two-pass counter reduces auxiliary bookkeeping to O(1) integers, though Python still needs O(n) space for the output character buffer because str is immutable. In a language with mutable strings or character arrays (such as C++ std::string or a char[] in C/Java), the left-to-right pass and right-to-left compaction pass can overwrite the array in place using read/write pointers in true O(1) extra space.

Follow-up questions

Similar questions

More Eightfoldai interview questions

All 2 Eightfoldai questions →