Fewest Bracket Deletions That Make a Query Expression Valid

Last updated: November 29, 2026

Quick Overview

A search query builder receives expressions with unbalanced parentheses and other characters. Remove the minimum number of parentheses so the result is balanced, and return every distinct result achievable with that minimum.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


A search query builder receives expressions with unbalanced parentheses and other characters. Remove the minimum number of parentheses so the result is balanced, and return every distinct result achievable with that minimum.

A hard Google onsite problem in which the minimum and the full set of answers both matter. The interviewer checks that you compute exactly how many opens and closes must go before searching, then prune with those budgets and skip duplicate removals.

What the Interviewer Expects
  • Computes the exact number of extra '(' and ')' to remove in one linear pass
  • Backtracks with those removal budgets instead of exploring every subset
  • Skips removing a bracket that equals the previous character at the same level to avoid duplicate results
  • Validates the final string or tracks balance during the search
  • Contrasts with the BFS-by-level approach
Key Topics to Cover
Backtracking
Parentheses balance
Pruning
Deduplication
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return just one valid result in O(n).
  • Compare the BFS approach that removes one character per level.
  • How would you extend this to brackets of three types?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: string with (, ), and letters, length up to about 25.
  • Output: all distinct strings obtained by deleting the minimum number of parentheses such that the result is balanced.
  • Example: `"...
High-Level Design
  1. Count what must go. Scan left to right with open_needed: on ( increment; on ) decrement if positive, else this close is unmatched so rm_close += 1. At the end, rm_open = open_needed. The ...

Submit Your Answer
Markdown supported