Python coding

Longest well-formed parentheses stretch

s contains only the characters ( and ). A stretch is well formed when it has as many ( as ) and, read from left to right, never has more ) than ( so far, like "(()())" or "()()". Return the length of the longest contiguous well-formed stretch of s, or 0 if there is none.

Aim for O(n): checking every stretch is O(n²) at best.

Besides the tests, one large input (6,000 parentheses) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_well_formed("(()") → 2
  • longest_well_formed(")()())") → 4
  • longest_well_formed("()(())") → 6
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Push the index of each (. A ) pops its match; the index left on top then sits just before the well-formed stretch that ends here.

Hint 2

Start the stack with -1, so a stretch that begins at index 0 has a left edge. The stretch ending at i has length i - stack[-1].

Hint 3

A ) that empties the stack has no match, so no stretch can cross it. Push its index as the new left edge.

Solution and why it works
pythonO(n) · O(n)
def longest_well_formed(s: str) -> int:
    best, stack = 0, [-1]          # bottom: the index just before the current stretch
    for i, ch in enumerate(s):
        if ch == "(":
            stack.append(i)
        else:
            stack.pop()                # the matching "(", or the old left edge
            if stack:
                best = max(best, i - stack[-1])
            else:
                stack.append(i)        # unmatched ")": the next stretch starts after it
    return best

After a ) pops its match, the top of the stack is the last index that cannot belong to the current stretch: a ( still waiting, or an unmatched ). So i - stack[-1] is the longest well-formed stretch ending at i, and neighbours like ()(()) join on their own. Each index is pushed and popped once: O(n). Traps: leaving out the -1 base (a stretch from index 0 then has no left edge), and not pushing the index of a stray ).