Day 34 of 90CF 1400Codeforces

Regular Bracket Sequence

Delete as few brackets as possible from a string of ( and ) so that what's left is balanced, and print the length that remains.

Pattern
Greedy matching with a counter
Time box
25 min
Time
O(n)
Space
O(1)

Try it first — give it 25 minutes

0/4 revealed

Stuck? Take one hint at a time. The struggle is where the pattern sticks.

    The problem in plain English

    You get one line: a non-empty string of ( and ), up to 10⁶ characters long. A bracket sequence is regular if it's balanced: reading left to right, you never close more than you've opened, and by the end everything is closed.

    You may delete any characters you like, without changing the order of the rest. Print the maximum length of a regular sequence you can end up with. (The empty string counts as regular, so the answer can be 0.)

    This is a Codeforces problem, so you read from standard input and print to standard output.

    Example: (()))( → 4. Delete the third ) and the final ( to get (()).

    Start with brute force

    Try every subset of characters to keep, check whether the result is regular, and remember the longest.

    It's correct, but a string of length n has 2ⁿ subsets. Even n = 40 means about 10¹² subsets, and here n can be 10⁶. We need to decide about each character on the spot.

    Building the intuition

    Walk through (()))( and think about each character as you meet it.

    • An opener ( is never a problem yet. It might get closed later. Keep it as "waiting".
    • A closer ) needs a waiting ( to its left. If there is one, pair them: both can stay.
    • If a ) arrives and nothing is waiting, no deletion choice can save it. Every ( before it is already paired with some earlier ). Unpairing one of them to free it would only swap which ) you keep, not add a pair. So drop it.

    At the end, any ( still waiting never got closed. Drop those too.

    In Valid Parentheses you needed a stack, because there were three bracket types and the top told you which type was waiting. Here there's only one type, so all the stack would ever tell you is how many are waiting. A stack of identical items is just a counter. That's the whole trick: the stack shrinks to one integer.

    The optimal approach

    1. Read the string s. Set open = 0 (waiting openers) and matched = 0 (length kept).
    2. For each character:
      • (: open += 1.
      • ) with open > 0: pair it. open -= 1, matched += 2.
      • ) with open == 0: drop it. Do nothing.
    3. Print matched. The leftover open openers are never counted, which is the same as deleting them.

    The subtle detail is why greedy pairing is safe. Pairing a ) with a waiting ( immediately can't hurt a later ). If a later ) had wanted that same (, then this ) and that one could simply swap partners. The number of pairs stays the same. So taking every pair as soon as it's available gives the maximum.

    The code

    Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.

    import sys
    
    
    def main():
        s = sys.stdin.readline().strip()
        open_count = 0  # '(' kept so far that are still waiting for a ')'
        matched = 0     # length of the regular sequence we keep
    
        for c in s:
            if c == "(":
                open_count += 1
            elif open_count > 0:
                # pair this ')' with any waiting '(' and keep both
                open_count -= 1
                matched += 2
            # else: a ')' with nothing to close can never be part of the answer, drop it
    
        # the leftover open_count brackets are never closed, so they are dropped too
        print(matched)
    
    
    main()

    Dry run

    s = "(()))("

    icharopen beforeactionopen aftermatched
    0(0wait10
    1(1wait20
    2)2pair12
    3)1pair04
    4)0nothing waiting → drop04
    5(0wait14

    The last ( is still waiting at the end, so it's dropped. Print 4.

    Complexity

    • Time: O(n). One pass over at most 10⁶ characters.
    • Space: O(1) besides the input string. Two integers replace the whole stack.

    Edge cases and traps

    • Counting ( and ) and printing 2 · min(count). That fails on )(: one of each, but nothing can pair, so the answer is 0. Order matters.
    • Forgetting the leftover openers. If you compute n − dropped closers, you count unclosed ( as kept. Only count pairs.
    • Slow input in Java or Python. 10⁶ characters is fine with BufferedReader.readLine() or sys.stdin.readline(). Avoid reading one character at a time through Scanner.
    • Trailing newline or \r. Strip the line before scanning, or only react to ( and ) as the loop above does.

    Say it in the interview

    "I scan left to right with a counter of unmatched opening brackets. An opener increases it. A closer can be kept only if some opener is waiting. Then I pair them, decrease the counter and add 2 to the answer. Otherwise the closer can never be matched, so I drop it. Openers left over at the end are dropped too. Greedy pairing is safe because swapping partners never changes the number of pairs. It's one pass, O(n) time and O(1) space, since with one bracket type the stack is just a count."

    Follow-ups interviewers ask

    • "Print the actual sequence, not just its length." Use a real stack of indices of (. Pair on ), mark both indices as kept, and output the kept characters in order.
    • "What's the longest regular substring (contiguous)?" That's a different problem. Keep a stack of indices, starting with a -1 sentinel, and measure i − stack.top after each successful pop.
    • "How many insertions would make the whole string regular?" It's the dropped closers plus the leftover openers: the same scan, just counting the other side.

    Practise the same idea

    This is Day 34 of a free 90-day plan 🐸

    90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.

    Get the full roadmap — free