ProgrammingVery hardCognizant GenC · TCS NQT

What is printed?

What is printed?
def longest(s):
    st = [-1]
    best = 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(')()())'), longest('(()'))
  1. A. 2 2
  2. B. 4 1
  3. C. 4 2
  4. D. 6 2

Correct answer: C. 4 2

A stack of indices marks where the current valid run starts. The longest valid run in )()()) is ()() with length 4, and (() contains the valid pair () of length 2.

More Python Programming questions

Exams that ask this topic