KatInterview

Balanced Parentheses After Digit-Driven Removals

Dynamic ProgrammingAuto-graded · 28 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingstringsparentheses

Last 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

  • s contains only (, ) and 0-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.