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
sis'(',')', or a lowercase English letter ('a'–'z').
Step-by-step walkthrough
Understand what makes a parentheses string valid
We are given a string
smade 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
+1at every'(', subtract-1at every')', and ignore letters. - The string is valid if
balancenever drops below0(every')'has an earlier'('to close) and ends at0(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 index2with')'at index4and drops the leftover'('at index0, producing"x(y)z".- Start with
Why brute force is too slow
A brute-force search tries removing
0parentheses, then every single parenthesis (1removal), then every pair (2removals), and stops as soon as a valid string appears. Ifscontainspparentheses, there are2^psubsets in the worst case — atp = 30,2^30is already over a billion combinations, whereasscan have100,000characters.We only keep that subset search inside
tests.pyon tiny random strings (up to length 10) to cross-check our linear-time algorithm.Key idea: greedily pair each ')' with the nearest open '('
Scan
sonce from left to right while maintaining a stack — a last-in, first-out list whereappendpushes a new item on top andpopremoves the most recent item:- When we see
'(', push its index ontoopen_indices. - When we see
')':- If
open_indicesis non-empty, pop the top index. That')'and that'('now form a valid matched pair, so we keep both. - If
open_indicesis empty, there is no free'('anywhere to its left. This')'can never be matched, so we record its index inindices_to_remove.
- If
- After the scan finishes, any index still sitting in
open_indicesis an'('that never found a')'to its right. Record all of those inindices_to_removetoo.
Why is this guaranteed to delete the minimum possible number of parentheses?
- Suppose the scan marks
Runmatched')'characters. When theR-th one is marked at indexi, every'('ins[0..i]has already been paired, meaning that prefix containsRmore')'than'('. Every valid output must delete at leastRclosers insides[0..i]. - Suppose
mpairs matched andLopeners remain on the stack. Thenshasm + Lopeners andm + Rclosers. Since at leastRclosers must be deleted, at mostmpairs can survive in any valid output, which forces at leastLopeners to be deleted as well.
So no valid solution can delete fewer than
R + Lcharacters, and our greedy pass deletes exactlyR + Lwhile leavingmproperly nested pairs.- When we see
Phase 1: find every unmatched ')' and '(' index
Notice a crucial detail:
open_indicesstores integer positions (like3), not the character'('. All'('characters look identical, so if we only pushed'(', we wouldn't know which'('inswent 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)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 toncharacters on every deletion and degrades toO(n^2)time on inputs like")))))...".Instead, we test
i not in indices_to_removeinO(1)average time per character, collect surviving characters in a Pythonlist, and call"".join(kept_chars)once at the end inO(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)Trace Example 4 and Example 1 with a pointer diagram
Let's trace Example 4,
s = "()())(()"(indices0..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_indicesis empty ->indices_to_remove.add(3).i = 5('(') andi = 8('('):open_indicesbecomes[5, 8].i = 11(')') pops8, andi = 13(')') pops5-> both nested pairs match!- End of loop:
open_indicesis empty, so only index3is omitted, producing"algo(ri(th)m)".
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:
i = 0('('): push0onto the stack (open_indices = [0],indices_to_remove = {}).i = 1('x'): letter, leave alone.i = 2('('): push2onto the stack (open_indices = [0, 2]).i = 3('y'): letter, leave alone.i = 4(')'): stack is non-empty, so pop2(open_indices = [0]), pairing indices2and4;i = 5('z') is left alone. After the loop,0remains onopen_indices, so add0toindices_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 thencharacters once to match parentheses (pushing and popping each index at most once inO(1)time), copy up tonleftover stack indices intoindices_to_remove, and scansone more time withO(1)average-time set lookups before a singleO(n)"".join(...). - Space:
O(n). In the worst case (such as"(((..."or")))..."),open_indices,indices_to_remove, andkept_charseach hold up tonitems.
Edge cases
- Empty string or letters only (
"","abc"): Bothopen_indicesandindices_to_removestay 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 index2pairs with index4, returning"x(y)z". - Deep nesting (
50,000nested'('): 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 toncharacters, turningO(n)deletions intoO(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_countinteger, skipping any')'that arrives whenopen_count == 0. At the end of Pass 1,open_countequals the number of extra'('characters. Pass 2 scans the surviving list right to left and drops the firstopen_count'('characters it sees (the rightmost ones), then reverses the list. Both time and space remainO(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 = 0andunmatched_close = 0. Incrementopen_counton'('; on')', decrementopen_countifopen_count > 0, otherwise incrementunmatched_close. Returningunmatched_close + open_countruns inO(n)time andO(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 countclose_budget(theRexcess')') andopen_budget(theLexcess'('). In a left-to-right pass, whenever'('arrives right after kept')'characters and we still have unusedclose_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 lastL'('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 needsO(n)space for the output character buffer becausestris immutable. In a language with mutable strings or character arrays (such as C++std::stringor achar[]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 trueO(1)extra space.
Follow-up questions
- How would your solution change if you only needed to compute the minimum deletion count instead of building the valid string?
- When several minimum-deletion strings are valid, how could you guarantee returning the alphabetically (lexicographically) first one?
- Is it possible to achieve O(1) auxiliary memory, and how does string mutability in the host language affect that bound?
Similar questions
- Framing Your Current Role, Career Growth, and Job Moves
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One