Data Structures & AlgorithmsVery hardCodeforces Div2 D · GATE CS

What is the length of the longest well-formed (valid) parentheses substring of "()(()())))(()"?

  1. A. 10
  2. B. 12
  3. C. 8
  4. D. 9

Correct answer: C. 8

Use a stack of indices seeded with −1: on '(' push its index, on ')' pop and measure from the new top (or push the index if the stack empties). Counting matched pairs across the whole string overcounts substrings that are not contiguous.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic