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
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

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
backtracking
string parsing
pruning
balanced parentheses
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
  • 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 Problems
Sample 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...


Submit Your Answer
Markdown supported