Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the length of the longest valid (well-formed) parentheses substring.

Problem: Find the length of the longest valid (well-formed) parentheses substring.
def longest_valid(s):
    st, best = [-1], 0
    for i, ch in enumerate(s):
        if ch == '(':
            st.append(i)
        else:
            st.pop()
            if not st: st.append(i)
            else: best = max(best, i - st[-1])
    return best
print(longest_valid(")()())"), longest_valid("(()(()"), longest_valid("()(())"))
What is printed?
  1. A. 4 2 6
  2. B. 4 4 6
  3. C. 4 2 4
  4. D. 2 2 6

Correct answer: A. 4 2 6

The stack bottom holds the index just before the current valid run. ")()())" → "()()" = 4. In "(()(()" the unmatched '(' at index 3 splits the string, so the best is 2, not 4. "()(())" is entirely valid → 6. O(n).

More Coding Interview Problems questions

Exams that ask this topic