Remove Invalid Parentheses

HardBacktrackingbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s made of '(', ')', and lowercase letters. A string is valid if its parentheses are balanced: scanning left to right, the number of ')' never exceeds the number of '(', and the counts are equal at the end. Letters are ignored. Remove the minimum possible number of parentheses so that the string becomes valid, and return every distinct valid string achievable with exactly that minimum number of removals. Return the strings in any order, each exactly once. If the only option is removing every parenthesis and nothing remains, the answer contains the empty string "".

Examples

Input: s = "()())()"
Output: ["(())()","()()()"]
One removal is required, and exactly these two distinct strings result.
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
Letters stay in place; one ")" must go.
Input: s = ")("
Output: [""]
Both characters must be removed, leaving the empty string.

Constraints

  • 1 <= s.length <= 20
  • `s` consists of lowercase English letters and parentheses
  • There are at most 20 parentheses in `s`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems