DSA and coding Level 2 This level · 27 of 30
Medium dsa stack

Minimum Remove to Make Valid Parentheses

The 30 second answer

I walk the string and remember the indices of unmatched opening parentheses on a stack. An unmatched closer is marked for deletion immediately, and anything still on the stack at the end is an unmatched opener, also marked. I then rebuild the string without those indices. Letters are copied through unchanged.

Could you say this in an interview?

Problem Given a string of lowercase letters and the characters '(' and ')', delete the fewest parentheses so that the remaining string is valid, and return any one such result. Letters are never deleted. Original: LeetCode 1249: Minimum Remove to Make Valid Parentheses.

Understanding the prompt Valid means the same rules as Valid Parentheses, with letters ignored for matching. There can be more than one correct answer; any minimum deletion is accepted. Deleting all parentheses is always valid, but it is rarely minimal.

Pattern recognition Stack matching on indices rather than on the characters themselves, so you know which positions to drop.

Brute force Try every subset of parentheses to delete, from smallest to largest, and return the first valid string: exponential.

Optimal A stack of indices of still-open '(' characters, and a set of indices to drop. A ')' with an empty stack is dropped; a ')' that can pop is fine. After the scan, every index left on the stack is a leftover '(' and is also dropped. Then build the string from the characters whose indices are not in the set. This problem is named in a public Meta E4 interview report.

Alternatives Two passes without a set: walk left to right and drop extra ')', then walk right to left and drop extra '('. The stack-of-indices version makes the deletions obvious.

Java solution

import java.util.ArrayDeque;
import java.util.HashSet;

public class MinimumRemoveToMakeValidParentheses {
    static String minRemoveToMakeValid(String s) {
        var st = new ArrayDeque<Integer>();
        var drop = new HashSet<Integer>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') st.push(i);
            else if (c == ')') {
                if (st.isEmpty()) drop.add(i);
                else st.pop();
            }
        }
        drop.addAll(st);
        var sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!drop.contains(i)) sb.append(s.charAt(i));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(minRemoveToMakeValid("lee(t(c)o)de)")); // lee(t(c)o)de
        System.out.println(minRemoveToMakeValid("a)b(c)d"));       // ab(c)d
        System.out.println(minRemoveToMakeValid("))(("));          // (empty)
    }
}

Complexity O(n) time, O(n) extra space for the stack, the drop set and the output.

Edge cases

  • A trailing extra closer, as in "lee(t(c)o)de)", becomes "lee(t(c)o)de".
  • A closer before any opener, as in "a)b(c)d", becomes "ab(c)d".
  • Only unmatched brackets, as in "))((", become the empty string.

Follow-ups

  • Valid Parentheses is the yes/no version with no letters.
  • Return the number of deletions instead of the cleaned string: that is the size of the drop set.

Tests "lee(t(c)o)de)" returns "lee(t(c)o)de". "a)b(c)d" returns "ab(c)d". "))((" returns "".

How to say it in the interview "I store indices of unmatched opening parentheses on a stack. A closer with nothing to match is marked for deletion, and leftover openers at the end are marked too. Then I rebuild the string without those indices. Linear time."

Sources (3)
  1. LeetCode 1249: Minimum Remove to Make Valid Parenthesesleetcode.com
  2. Java SE 17 API: HashSetdocs.oracle.com
  3. LeetCode Discuss: Meta E4 interview experience (candidate report, March 2025)leetcode.com
Previous
Next