← Questions

Remove invalid parentheses: every minimal result

0
MetaCodingLast asked Apr 2026

A coding interview question asked in Meta's technical phone screen, last asked Apr 2026. It tests backtracking, bfs and strings.

A string contains lowercase letters and the characters ( and ). Remove the fewest parentheses so the rest is valid, and return every distinct valid string you can get with that minimum number of removals. Letters stay in place and don't affect validity.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • remove_invalid_parentheses(s: str) -> list[str] — every distinct result, sorted lexicographically. A string with no valid non-empty result returns [""].

Example

remove_invalid_parentheses("()())()")   ->  ["(())()", "()()()"]
remove_invalid_parentheses("(a)())()")  ->  ["(a())()", "(a)()()"]
remove_invalid_parentheses(")(")        ->  [""]

Constraints

  • 0 <= len(s) <= 25; at most 20 parentheses.

Clarifying questions

  • Should results be distinct, and in which order?
  • What is returned when everything must be removed?
  • Can letters other than lowercase appear?

What a strong answer covers

  • First count how many ( and ) must go: one left-to-right pass counting unmatched closers, plus openers left over.
  • Backtracking that removes exactly that many of each kind, skipping duplicate removals in runs of the same character and pruning when the running balance goes negative.
  • The BFS alternative: remove one parenthesis at a time level by level, stopping at the first level that has valid strings, with a seen-set to avoid repeats.
  • The worst-case cost (exponential in the number of parentheses) and why pruning matters.
  • Tests: already valid, all closers, letters only, nested invalid parentheses.

Follow-ups

  • Return just one valid result with the fewest removals in O(n) (a stack of opener indices).
  • Count the minimum removals without producing strings.
  • Support several bracket types: (), [], {}.

Where it's asked

  • Meta · Technical phone screen · Last asked Apr 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

backtracking · bfs · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding