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:
- Walk through
sfrom index0toward the end, dropping each')'encountered while zero unmatched'('characters are open ahead of it. - 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
sis an English letter (a–z,A–Z), an ASCII digit (0–9),'(', or')'.
Step-by-step walkthrough
Understand balanced parentheses and the tie-breaking rule
A string has balanced parentheses when two rules hold at the same time:
- Reading from left to right, the number of closing
)seen so far never exceeds the number of opening(seen so far. - 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- Reading from left to right, the number of closing
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. Ifscontainsmparentheses, there are2^msubsets to inspect, which becomes astronomically slow long befores.lengthreaches100,000.Instead, notice that we never have to guess:
- Whenever a left-to-right scan meets a
)while0unmatched(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 iskextra(characters (k >= 0). Deletingkopening parentheses achieves the exact minimum number of deletions.
- Whenever a left-to-right scan meets a
Pass 1: discard impossible closing parentheses left to right
Walk through
sfrom left to right with an integer counterunmatched_openthat tracks how many kept(are still waiting for a matching):- On
'(': incrementunmatched_openand append'('tofirst_pass_chars. - On
')': ifunmatched_open > 0, pair it with one waiting'('(unmatched_open -= 1) and keep')'; ifunmatched_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 = 0first_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 == 0after Pass 1, every kept(already found a)partner, so"".join(first_pass_chars)is immediately balanced!- On
Pass 2: why dropping excess `(` from right to left stays balanced
Suppose
unmatched_open > 0after Pass 1 — say Pass 1 kept5'('and3')', sounmatched_open = 2. Following Rule 2, we scanfirst_pass_charsfrom right to left and skip the first2'('characters we encounter, keeping the leftmost3'('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: all3kept'('are already behind us, and the entire string only contains3')'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)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 ""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 thencharacters once inO(1)work per character; Pass 2 visits at mostnkept characters in reverse, reverses the list inO(n), and joins the characters into a string inO(n). - Space:
O(n). The character listsfirst_pass_charsandreversed_kepthold at mostnsingle-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_openstays0, every character is kept in Pass 1, and the fast path returns"Report2026"untouched. - All parentheses unmatched (
")))((","((((","))))"): Pass 1 discards every)whenunmatched_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 += chorch + result): Prependingch + resultin Pass 2 copies the entire string on every character, degradingO(n)intoO(n^2)and timing out on100,000characters. Always append to alistand call"".join(...)once. - Deleting excess
(from left to right in Pass 2: Dropping the earliest(can break balance! For example, on"()(", Pass 1 keeps"()("withunmatched_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 index0unmatched 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 ato_removehash set — an unordered collection supportingO(1)average membership checks — when the stack is empty), and add any leftover stack indices intoto_removeat the end before rebuilding the string. Both approaches run inO(n)time andO(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 substringss[i..j]so each subproblem is computed only once), which takesO(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
- Suppose any minimum-deletion valid string is accepted—how would you solve this using an explicit stack of indices?
- Why does a simple open-parenthesis counter break down if square `[]` and curly `{}` brackets are also included?
- How would you change the algorithm if you had to return all unique balanced strings reachable with the minimum number of deletions?
Similar questions
- Balanced BST from Ascending Linked Nodes
- Single-Typo Dictionary Word Matching
- Multi-Head Attention Forward Pass in NumPy
- Dot Product of Run-Compressed Vectors
- Mutual-Friend Recommendation
- Single-Transaction Stock Profit
More Meta interview questions
- Bipedal Dinosaur Speed Leaderboard Medium
- Binary Tree Lowest Common Ancestor Medium
- Palindrome Check Under a Deletion Budget Medium Pro
- Moving Averages Over Fixed-Width Subarrays Easy Pro
- Merge Two Sorted Lists of Disjoint Intervals Medium Pro
- Mutual-Friend Recommendation Medium Pro
- Daily Active Ad Revenue by Source Easy Pro
- Subarray Sum Existence with Negatives Medium Pro
- Shortest Maze Path with Keys and Doors Medium Pro
- Multi-Stage Stateful In-Memory Service Simulations Easy Pro