KatInterview

Identify Invalid Parentheses for Removal

Stacks & QueuesAuto-graded · 25 test cases
MediumAuto-gradedStacks & Queuesstackstring-processinggreedy

Last updated

Tests stack-based matching to find the minimum set of parenthesis indices that must be removed to balance a string.

You are given a string s containing lowercase letters and parentheses characters ( and ). Your task is to determine which parentheses must be removed to make the string valid.

A valid string satisfies these rules:

  • Every opening parenthesis ( has exactly one matching closing parenthesis ) that comes after it
  • Every closing parenthesis ) has exactly one matching opening parenthesis ( that comes before it
  • The parentheses are properly nested (no crossing matches)

Return a list of indices indicating which parentheses must be removed to achieve the minimum number of deletions. The indices should be in ascending order.

Use the greedy matching strategy: each closing parenthesis matches with the most recent unmatched opening parenthesis.

Constraints:

  • 1 <= len(s) <= 10^5
  • s contains only lowercase English letters and the characters ( and )
  • The solution must run in O(n) time

Examples

Example 1

Input: find_invalid_parens('a(b)c)')

Output: [5]

Example 2

Input: find_invalid_parens('()())')

Output: [4]

Example 3

Input: find_invalid_parens('abc')

Output: []

Example 4

Input: find_invalid_parens('((a))')

Output: []

Hints

Hint 1

Track unmatched opening parentheses as you scan left to right

Hint 2

A closing parenthesis with no available opening parenthesis to match must be removed

Hint 3

Any opening parenthesis that remains unmatched at the end must be removed