DSA Stacks

Minimum Remove to Make Valid Parentheses

Stack indices of unmatched openers; on close-without-opener, mark the closer for removal — then strip.

Medium
Time O(n) Space O(n)
LeetCode
4 min read
stack string

Problem#

Given a string of lowercase letters and parentheses, remove the minimum number of parentheses to make the parentheses valid. Return any resulting valid string.

Examples#

  • "lee(t(c)o)de)""lee(t(c)o)de"
  • "a)b(c)d""ab(c)d"
  • "))(("""

Constraints#

  • 1 <= s.length <= 10^5.

Approach#

Walk the string keeping a stack of indices of ( not yet matched. On ), if the stack is non-empty, pop (matched); else mark this index for deletion. At the end, any indices still on the stack are unmatched ( and must also go.

Solution#

Minimum Remove to Make Valid Parentheses
class Solution {
public:
string minRemoveToMakeValid(string s) {
stack<int> opens;
vector<bool> remove(s.size(), false);
for (int i = 0; i < (int)s.size(); ++i) {
if (s[i] == '(') opens.push(i);
else if (s[i] == ')') {
if (!opens.empty()) opens.pop();
else remove[i] = true;
}
}
while (!opens.empty()) { remove[opens.top()] = true; opens.pop(); }
string ans;
ans.reserve(s.size());
for (int i = 0; i < (int)s.size(); ++i)
if (!remove[i]) ans.push_back(s[i]);
return ans;
}
};

Editorial#

Two failure modes: too many closers (unmatched ) left-to-right) and too many openers (unmatched ( remaining at end). The stack catches the first; the leftover stack contents catch the second. We then strip exactly those marked indices.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.