15% off all plans & roadmaps Use code
See plansLeetCode 301 · Solution & editorial
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Remove Invalid Parentheses is a Backtracking Patterns problem, in the Parentheses Generation subpattern. The pattern covers subsets, permutations, combinations, N-Queens, and word search
Generate all valid parentheses combinations using backtracking with balance tracking.
The reference solution runs in O(C(n, c)) time and O(c) space.
Remove Invalid Parentheses has been reported in interviews at Facebook, Bloomberg, ByteDance, Amazon, Qualtrics.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Remove Invalid Parentheses is a Backtracking Patterns problem, in the Parentheses Generation subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.