Data Structures & AlgorithmsVery hardProduct Company SDE · stack round

Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code.

Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code.
s = ')()())'
st = [-1]
best = 0
for i, c in enumerate(s):
    if c == '(':
        st.append(i)
    else:
        st.pop()
        if not st:
            st.append(i)
        else:
            best = max(best, i - st[-1])
print(best)
What is printed?
  1. A. 2
  2. B. 4
  3. C. 6
  4. D. 0

Correct answer: B. 4

The substring '()()' at indices 1 to 4 is well-formed and has length 4. The stack stores the index before each valid block, so the distance gives its length.

More Coding Interview Problems questions

Exams that ask this topic