Balanced Parentheses After Digit-Driven Removals
Dynamic ProgrammingAuto-graded · 28 test casesLast updated
Decide whether removing parentheses to satisfy per-digit quotas can leave a balanced bracket string, using a DP over balance and removal count.
You are given a string s made only of the characters (, ) and the digits 0 through 9.
Every digit in the string places a demand on the parentheses to its left. A digit at position i with value v requires that exactly v parentheses located at positions strictly before i are removed on its behalf.
The rules are:
- Each parenthesis can be removed at most once, so no two digits may claim the same one.
- Digits are never removed. They are ignored when you judge the string afterward.
- A parenthesis can only be removed if some digit claims it. Removals that no digit claims are not allowed.
After every digit has had its demand met, read the surviving parentheses from left to right, skipping the digits. Return True if there is at least one way to choose the removals so that the surviving parentheses form a valid parentheses string. Otherwise return False.
A valid parentheses string is one where every ) is matched with an earlier unmatched (, and no ( is left unmatched at the end. The empty sequence is valid.
If the digits ask for more removals than there are available parentheses, the answer is False. A string with no parentheses and only zeros, or an empty string, gives True.
Implement the function so it returns a boolean.
Constraints
scontains only(,)and0-9.0 <= len(s), and the length is small enough for a cubic-time solution (up to a few hundred characters).- Only the yes/no answer is required, not the actual removals.
Examples
Example 1
Input: can_balance_after_removals('()')
Output: True
Example 2
Input: can_balance_after_removals('(1)')
Output: False
Example 3
Input: can_balance_after_removals('(())2')
Output: True
Example 4
Input: can_balance_after_removals('1()')
Output: False
Hints
Hint 1
Think about which parentheses each digit ends up using. Because every digit looks at a prefix of the string, you only need to know how many parentheses have been removed so far, not which ones.
Hint 2
Scan left to right and track pairs (balance of kept parentheses, number removed so far). For each parenthesis you either keep it, which updates the balance and must never push it below zero, or remove it, which increases the removed count.
Hint 3
Keep a running sum of digit values. At each digit, discard states whose removed count is below that running sum. At the end, accept only a state with balance 0 and removed count exactly equal to the total of all digits.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reduce the assignment to counting. Every removal exists only because some digit claims it, so the total number of removals must equal T, the sum of all digit values.
Suppose we have chosen a set D of parentheses to remove. Can the removals be handed out to digits so that each digit gets exactly its quota from its left side? The digits' allowed regions are nested prefixes, since a later digit can use anything an earlier digit can. By a Hall-style or greedy argument, an assignment exists exactly when:
- At each digit, the number of removed parentheses before it is at least the sum of the quotas of all digits up to and including it.
- The total
|D|equalsT.
So we never need to know which digit owns which removal, only how many removals have happened so far.
DP over states (balance, removed). Scan left to right, keeping the set of reachable pairs:
(: remove it, giving(b, d+1), or keep it, giving(b+1, d).): remove it, giving(b, d+1), or keep it ifb > 0, giving(b-1, d).- digit
v: addvtorequired, then drop every state withd < required. Parentheses to the right cannot help this digit.
At the end, return True if some state has balance == 0 and removed == required, where required now equals T.
Why it is correct
- Completeness. Any removal set that works corresponds to one path of keep/remove choices. Its kept parentheses never go negative and end at 0. Because the set is assignable, it satisfies the prefix condition at every digit, so it survives every filter and ends with
removed = T. - Soundness. A surviving final state with balance 0 comes from a valid kept sequence. It satisfies the prefix condition at every digit and removes exactly
Tparentheses, so a legal assignment of removals to digits exists. - Why
>=at digits but==at the end. Early surplus removals can be claimed by later digits, which is legal. The final equality rules out removals that no digit claims. For example,"()1"fails because one removal leaves an unmatched parenthesis.
Pruning states with removed > T is safe, since such states can never end with equality.
Complexity
- Balance and removed count are each at most
n, so there are O(n²) states. - Each character processes every state in O(1).
- Time: O(n³) worst case. Space: O(n²).
Reference solution
from typing import Set, Tuple
def can_balance_after_removals(s: str) -> bool:
# State: (balance of kept parentheses, number of parentheses removed so far)
states: Set[Tuple[int, int]] = {(0, 0)}
required = 0 # running sum of digit values seen so far
total_demand = sum(int(c) for c in s if c.isdigit())
for ch in s:
if ch.isdigit():
required += int(ch)
# Removals made before this digit must cover all demand up to here.
states = {(b, d) for b, d in states if d >= required}
elif ch == "(":
nxt = set()
for b, d in states:
if d + 1 <= total_demand:
nxt.add((b, d + 1)) # remove it
nxt.add((b + 1, d)) # keep it
states = nxt
else: # ch == ")"
nxt = set()
for b, d in states:
if d + 1 <= total_demand:
nxt.add((b, d + 1)) # remove it
if b > 0:
nxt.add((b - 1, d)) # keep it, matching an open paren
states = nxt
return any(b == 0 and d == required for b, d in states)