Remove the Fewest Brackets to Balance a Message Template

Last updated: November 29, 2026

Quick Overview

A message template contains letters plus '(' and ')'. Remove the minimum number of parentheses so the remaining string is balanced, and return any one valid result.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Medium

0

0

0 solved


A message template contains letters plus '(' and ')'. Remove the minimum number of parentheses so the remaining string is balanced, and return any one valid result.

This is one of the most frequently practiced Meta screen problems, framed here as cleaning up user-authored templates. The interviewer wants an O(n) two-pass or stack solution, a clear argument that the removal count is minimal, and tidy code with no quadratic string building.

What the Interviewer Expects
  • Identifies unmatched ')' during a left-to-right scan
  • Identifies leftover unmatched '(' after the scan
  • Removes exactly those characters and argues minimality
  • Builds the output with a list, not repeated concatenation
  • Preserves non-bracket characters and their order
Key Topics to Cover
Stack
Strings
Greedy
Parentheses matching
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 all valid strings with the minimum removals (the hard BFS version).
  • Do it with O(1) extra space besides the output.
  • Extend to multiple bracket types like [] and {}.
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 up to 10^5 characters. Output any balanced string obtainable with the fewest deletions. Letters stay untouched. Target O(n) time....

High-Level Design

A ')' is unmatchable if, at the moment it appears, there is no open '(' before it; it must be removed. After the scan, any '(' still open has no partner to its right and must be removed. Keep a stack ...


Submit Your Answer
Markdown supported