Balance Parentheses with Fewest Deletions

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You receive a string s made up of alphanumeric characters (a–z, A–Z, 0–9) mixed with '(' and ')' characters. Your goal is to delete the fewest parentheses necessary so that all remaining parentheses in the string are properly nested and matched. Inserting new characters or rearranging existing ones is not permitted, and every letter and digit must stay in the output.

Whenever multiple strings achieve the same minimum deletion count, resolve ties using this exact two-stage procedure:

  1. Walk through s from index 0 toward the end, dropping each ')' encountered while zero unmatched '(' characters are open ahead of it.
  2. Walk backward from the end of the surviving characters toward index 0, dropping any excess '(' characters that still lack a matching ')'.

Return the resulting string formed by the surviving characters in sequence.

Examples

Example 1

  • Input: s = "cal(c(2)x)9)"
  • Output: "cal(c(2)x)9"
  • Explanation: Both '(' characters pair cleanly with the first two ')' characters, leaving zero open parentheses before the final ')'. Dropping only that last ')' yields a valid string in one deletion.

Example 2

  • Input: s = "m)n(p(q)r"
  • Output: "mn(pq)r"
  • Explanation: During the forward sweep, the ')' right after 'm' has no prior '(' and is dropped, leaving "mn(p(q)r" with two '(' and one ')'. During the backward sweep, the rightmost '(' (immediately before 'q') is dropped first, producing "mn(pq)r".

Example 3

  • Input: s = ")))(("
  • Output: ""
  • Explanation: All three leading ')' characters are dropped on the forward pass because no '(' precedes them, and both trailing '(' characters are dropped on the backward pass because no ')' follows them.

Constraints

  • 1 <= len(s) <= 100,000
  • Every character of s is an English letter (a–z, A–Z), an ASCII digit (0–9), '(', or ')'.

Step-by-step walkthrough

  1. Understand balanced parentheses and the tie-breaking rule

    A string has balanced parentheses when two rules hold at the same time:

    1. Reading from left to right, the number of closing ) seen so far never exceeds the number of opening ( seen so far.
    2. By the end of the string, the total number of ( equals the total number of ).

    Letters and digits are always kept in their original order, and we must delete as few parentheses as possible. Sometimes more than one minimum-deletion answer exists — for example, in "(a(b)", deleting the first ( gives "a(b)" while deleting the second ( gives "(ab)". To pick one answer deterministically, the problem specifies two passes:

    Pass 1 (left -> right):  discard every ')' that has no unmatched '(' before it
    Pass 2 (right -> left):  discard any still-unmatched '(' from right to left
    
  2. Why trying every deletion subset is too slow

    A brute-force check tries keeping or deleting each parenthesis (for example, recursively branching two ways on every ( or )) until a balanced result appears. If s contains m parentheses, there are 2^m subsets to inspect, which becomes astronomically slow long before s.length reaches 100,000.

    Instead, notice that we never have to guess:

    • Whenever a left-to-right scan meets a ) while 0 unmatched ( are waiting, nothing to its right can ever rescue that ), because we cannot add or reorder characters. Every valid solution must delete it.
    • Once all such impossible ) are gone, every ) in the remaining string can be paired, and the only remaining issue is k extra ( characters (k >= 0). Deleting k opening parentheses achieves the exact minimum number of deletions.
  3. Pass 1: discard impossible closing parentheses left to right

    Walk through s from left to right with an integer counter unmatched_open that tracks how many kept ( are still waiting for a matching ):

    • On '(': increment unmatched_open and append '(' to first_pass_chars.
    • On ')': if unmatched_open > 0, pair it with one waiting '(' (unmatched_open -= 1) and keep ')'; if unmatched_open == 0, discard it.
    • On any letter or digit: always append it.
    s = "x)y(z)9"
      'x' -> keep 'x'          (unmatched_open = 0)
      ')' -> DISCARD           (unmatched_open == 0, no '(' before it to match)
      'y' -> keep 'y'          (unmatched_open = 0)
      '(' -> keep '('          (unmatched_open = 1)
      'z' -> keep 'z'          (unmatched_open = 1)
      ')' -> keep ')'          (unmatched_open = 0)
      '9' -> keep '9'          (unmatched_open = 0)
    first_pass_chars = ['x', 'y', '(', 'z', ')', '9'],  unmatched_open = 0
    
    first_pass_chars: List[str] = []
    unmatched_open = 0
    
    for ch in s:
        if ch == "(":
            unmatched_open += 1
            first_pass_chars.append(ch)
        elif ch == ")":
            # A ')' seen when unmatched_open == 0 has no '(' before it and can never be matched later.
            if unmatched_open > 0:
                unmatched_open -= 1
                first_pass_chars.append(ch)
        else:
            first_pass_chars.append(ch)
    

    If unmatched_open == 0 after Pass 1, every kept ( already found a ) partner, so "".join(first_pass_chars) is immediately balanced!

  4. Pass 2: why dropping excess `(` from right to left stays balanced

    Suppose unmatched_open > 0 after Pass 1 — say Pass 1 kept 5 '(' and 3 ')', so unmatched_open = 2. Following Rule 2, we scan first_pass_chars from right to left and skip the first 2 '(' characters we encounter, keeping the leftmost 3 '(' characters.

    Why is keeping the leftmost 3 '(' guaranteed to leave every prefix valid? - Before the dropped section: we haven't deleted anything, and Pass 1 already ensured '(' never fell behind ')'. - From the dropped section onward: all 3 kept '(' are already behind us, and the entire string only contains 3 ')' in total — so '(' can never fall behind ')' here either!

    (By contrast, deleting excess '(' from the left would break "()(" into ")("!)

    s = "(a(b)"
    Pass 1 (left -> right):
      keeps ['(', 'a', '(', 'b', ')'],  unmatched_open = 1
    
    Pass 2 (right -> left):
      ')' -> keep ')'
      'b' -> keep 'b'
      '(' -> unmatched_open == 1 > 0 -> DISCARD, unmatched_open becomes 0
      'a' -> keep 'a'
      '(' -> unmatched_open == 0     -> keep '('
    reversed_kept = [')', 'b', 'a', '(']  --reverse-->  "(ab)"
    
    reversed_kept: List[str] = []
    for ch in reversed(first_pass_chars):
        if ch == "(" and unmatched_open > 0:
            unmatched_open -= 1
            continue
        reversed_kept.append(ch)
    
    reversed_kept.reverse()
    return "".join(reversed_kept)
    
  5. Walk through the examples

    Let's trace all three examples — Example 1 ("cal(c(2)x)9)", which finishes on the fast path), Example 2 ("m)n(p(q)r", which removes one ')' in Pass 1 and one '(' in Pass 2), and Example 3 (")))((", which removes everything):

    Example 1: s = "cal(c(2)x)9)"
      Pass 1:
        "cal" -> kept (unmatched_open = 0)
        "("   -> kept (unmatched_open = 1)
        "c("  -> kept (unmatched_open = 2)
        "2)"  -> kept (unmatched_open = 1)
        "x)"  -> kept (unmatched_open = 0)
        "9"   -> kept (unmatched_open = 0)
        ")"   -> DISCARDED (unmatched_open == 0)
      unmatched_open == 0 -> fast path returns "cal(c(2)x)9"
    
    Example 2: s = "m)n(p(q)r"
      Pass 1: discards ')' after 'm'; keeps ['m', 'n', '(', 'p', '(', 'q', ')', 'r'] with unmatched_open = 1
      Pass 2: scans right to left, discards '(' before 'q', keeps '(' before 'p' -> returns "mn(pq)r"
    
    Example 3: s = ")))(("
      Pass 1: discards all three ')' (unmatched_open == 0), keeps ['(', '('] with unmatched_open = 2
      Pass 2: scans ['(', '('] right to left, discards both '(' -> returns ""
    
  6. Complete solution

    Putting both passes together gives a linear-time solution that collects characters in Python lists and calls "".join(...) once at the end:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def makeParenthesesBalanced(s: str) -> str:
        # first_pass_chars: single-character strings kept after Pass 1, e.g. ['a', '(', 'b', ')']
        first_pass_chars: List[str] = []
        # unmatched_open: count of kept '(' so far that have not yet been paired with a ')'
        unmatched_open = 0
    
        # Pass 1 (left to right): keep letters/digits and '('; only keep ')' if an unmatched '(' precedes it.
        for ch in s:
            if ch == "(":
                unmatched_open += 1
                first_pass_chars.append(ch)
            elif ch == ")":
                # A ')' seen when unmatched_open == 0 has no '(' before it and can never be matched later.
                if unmatched_open > 0:
                    unmatched_open -= 1
                    first_pass_chars.append(ch)
            else:
                first_pass_chars.append(ch)
    
        # Fast path: if every kept '(' found a matching ')', Pass 1 already produced a balanced string.
        if unmatched_open == 0:
            return "".join(first_pass_chars)
    
        # Pass 2 (right to left): discard the rightmost `unmatched_open` opening parentheses.
        # Keeping the earliest '(' characters gives the maximum head start so '(' never drops below ')'
        # on any prefix, while removing `unmatched_open` openers makes total '(' equal total ')'.
        # reversed_kept: kept characters collected in right-to-left order before reversing at the end
        reversed_kept: List[str] = []
        for ch in reversed(first_pass_chars):
            if ch == "(" and unmatched_open > 0:
                unmatched_open -= 1
                continue
            reversed_kept.append(ch)
    
        # Restore original left-to-right character order before joining into the final string.
        reversed_kept.reverse()
        return "".join(reversed_kept)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of balanced parentheses like a venue with an entry gate ( and an exit gate ). Every exit ) needs someone already inside the venue to walk out; if 0 people are inside when an exit ) happens, that exit record is impossible and must be crossed off the log immediately. At the end of the day, if k people walked in through ( and never exited, we cross off the last k entry records from the end of the log so total entries equal total exits. That running headcount is called a prefix balance (the count of ( minus the count of ) seen from the start of the string up to the current position).

Why do naive approaches fail? Trying every combination of parentheses to delete checks up to 2^n subsequences (strings formed by deleting zero or more characters without changing the order of the rest), which times out completely once n exceeds ~25, let alone 100,000. Repeatedly slicing a Python string (s = s[:i] + s[i+1:]) whenever you spot a bad parenthesis is also too slow because each slice copies up to n characters, turning the runtime into O(n^2).

Let's walk through the 7-character example s = ")a(b(c)":

Input:  )  a  (  b  (  c  )

Pass 1 (left -> right, tracking unmatched_open):
  ')' -> unmatched_open is 0 -> discard!
  'a' -> keep 'a'   (unmatched_open = 0)
  '(' -> keep '('   (unmatched_open = 1)
  'b' -> keep 'b'   (unmatched_open = 1)
  '(' -> keep '('   (unmatched_open = 2)
  'c' -> keep 'c'   (unmatched_open = 2)
  ')' -> keep ')'   (unmatched_open = 1)
After Pass 1: ['a', '(', 'b', '(', 'c', ')'], with unmatched_open = 1

Pass 2 (right -> left, discarding 1 '('):
  ')' -> keep ')'
  'c' -> keep 'c'
  '(' -> discard! (unmatched_open drops from 1 to 0)
  'b', '(', 'a' -> all kept since unmatched_open == 0
Reverse & join -> "a(bc)"

Complexity

Let n be the length of s.

  • Time: O(n). Pass 1 visits each of the n characters once in O(1) work per character; Pass 2 visits at most n kept characters in reverse, reverses the list in O(n), and joins the characters into a string in O(n).
  • Space: O(n). The character lists first_pass_chars and reversed_kept hold at most n single-character strings before building the output string, while the balance state itself uses only one integer (unmatched_open).

Edge cases

  • No parentheses at all ("Report2026"): unmatched_open stays 0, every character is kept in Pass 1, and the fast path returns "Report2026" untouched.
  • All parentheses unmatched (")))((", "((((", "))))"): Pass 1 discards every ) when unmatched_open == 0, and Pass 2 discards every (, returning "".
  • Single-character input ("(", ")", "7"): Returns "" for a lone parenthesis and "7" for a single digit or letter.
  • Multiple minimum-removal choices ("m)n(p(q)r", "(a(b)", "((a)b(c)"): Pass 1 keeps all ( and counts excess openers; Pass 2 removes the rightmost (, deterministically producing "mn(pq)r", "(ab)", and "((a)bc)".

Common mistakes

  • Concatenating strings inside a loop (result += ch or ch + result): Prepending ch + result in Pass 2 copies the entire string on every character, degrading O(n) into O(n^2) and timing out on 100,000 characters. Always append to a list and call "".join(...) once.
  • Deleting excess ( from left to right in Pass 2: Dropping the earliest ( can break balance! For example, on "()(", Pass 1 keeps "()(" with unmatched_open = 1; deleting the leftmost ( yields ")(", which is invalid, whereas deleting from right to left yields "()".
  • Using a nearest-opener stack when the spec asks to discard excess ( from right to left: A stack (a last-in, first-out list that pairs each ) with the closest ( before it) leaves index 0 unmatched on "(a(b)" and returns "a(b)", whereas the problem's two-pass rule keeps earlier openers matched and discards excess ( from right to left to return "(ab)".

Follow-up questions

  • Suppose any minimum-deletion valid string is accepted—how would you solve this using an explicit stack of indices? Push the index of every ( onto a stack, pop when seeing ) (or add the ) index to a to_remove hash set — an unordered collection supporting O(1) average membership checks — when the stack is empty), and add any leftover stack indices into to_remove at the end before rebuilding the string. Both approaches run in O(n) time and O(n) total space, though our two-pass counter avoids allocating an auxiliary stack and index set.
  • Why does a simple open-parenthesis counter break down if square [] and curly {} brackets are also included? With multiple bracket types, integer counters are no longer enough even to count minimum deletions, because "([)]" has balanced counts for both () and [] yet crosses pairs illegally! Finding the minimum deletions across mixed bracket types requires dynamic programming (solving a problem by caching answers to smaller substrings s[i..j] so each subproblem is computed only once), which takes O(n^3) time for general longest balanced subsequence.
  • How would you change the algorithm if you had to return all unique balanced strings reachable with the minimum number of deletions? Model one-character deletions as edges in a graph and run Breadth-First Search (BFS) (exploring strings level by level in order of deletion count and stopping at the very first level that contains at least one balanced string), or compute the exact minimum counts of misplaced ( and ) first and run pruned backtracking while skipping duplicate deletions across consecutive identical parentheses.

Follow-up questions

Similar questions

More Meta interview questions

All 787 Meta questions →