Remove the Fewest Brackets to Make a Template Expression Valid
Last updated: November 29, 2026
Quick Overview
Seller-uploaded description templates use parentheses that may be unbalanced, and may contain other characters. Return every distinct string obtainable by removing the minimum number of parentheses so the result is balanced.
Amazon
November 29, 20260
0
0 solved
Seller-uploaded description templates use parentheses that may be unbalanced, and may contain other characters. Return every distinct string obtainable by removing the minimum number of parentheses so the result is balanced.
A hard onsite question in Amazon's style combining string scanning with backtracking. Interviewers look for computing exactly how many opens and closes must go first, then a pruned DFS that never removes more than necessary and avoids duplicate outputs.
What the Interviewer Expects
- Counts the minimum removals of ( and ) in one pass
- Backtracks only while removals remain
- Skips consecutive identical brackets to avoid duplicates
- Validates each candidate in linear time
- Contrasts with the BFS level-by-level approach
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you return just one valid result in O(n)?
- What is the worst-case number of results?
- How would you extend this to brackets of several types?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Characters other than ( and ) stay untouched. Remove as few brackets as possible; return all distinct results (sorted here for testing). Length up to about 25....
High-Level Design
First, one scan computes the exact minimum: unmatched ) seen while the balance is zero must be removed (close_extra), and leftover unmatched ( at the end must be removed (open_extra). Any vali...