Remove Invalid Parentheses (BFS)

Data Structures
Hard
Google
25.8K views

Given a string with parentheses, remove the minimum number of invalid parentheses to make the input string valid. Return all possible valid results. Use BFS.

Why Interviewers Ask This

Google asks this question to evaluate a candidate's mastery of graph traversal algorithms, specifically Breadth-First Search, in unstructured string spaces. It tests the ability to handle exponential search trees efficiently while minimizing operations. Interviewers look for candidates who can balance correctness with performance, ensuring they find all valid solutions without redundant computations or infinite loops.

How to Answer This Question

1. Clarify constraints: Confirm if the input contains only parentheses or other characters and define what 'valid' means (balanced pairs). 2. Define the BFS state: Explain that each node in your queue is a string, and edges represent removing one character. 3. Implement level-order processing: Iterate through the current queue level; generate neighbors by removing one invalid parenthesis at a time. 4. Validate early: Check validity immediately upon generation. If valid strings are found in the current level, stop generating further levels to ensure minimum removals. 5. Deduplicate results: Use a Set to store visited strings to prevent re-processing identical states, which is critical for performance on large inputs.

Key Points to Cover

  • Demonstrating understanding that BFS naturally finds the shortest path (minimum removals) in an unweighted graph
  • Explicitly mentioning the use of a Set to prevent revisiting duplicate states and avoid TLE
  • Clarifying the termination condition: stopping immediately after finding valid strings at the current depth
  • Explaining how to generate neighbors by iterating through the string and skipping non-parenthesis characters
  • Acknowledging the worst-case complexity but justifying why BFS is superior to DFS for finding minimum edits

Sample Answer

To solve the Remove Invalid Parentheses problem using BFS, I would first validate a helper function to check if a string has balanced parentheses. The core strategy involves treating every possible string modification as…

Common Mistakes to Avoid

  • Using Depth-First Search (DFS) without pruning, which fails to guarantee the minimum number of removals
  • Failing to deduplicate strings, leading to exponential time complexity and potential runtime errors
  • Not checking validity before adding to the queue, causing unnecessary queue growth
  • Ignoring the requirement to return ALL valid combinations instead of just one solution

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 166 Data Structures questionsBrowse all 145 Google questions