Data Structures & AlgorithmsVery hardProduct company OA

What is the length of the longest substring of ')()())(()())' that is a valid (balanced) parentheses string?

  1. A. 4
  2. B. 10
  3. C. 6
  4. D. 12

Correct answer: C. 6

Use a stack of indices with a sentinel for the last unmatched ')'. '()()' at indices 1–4 has length 4; the ')' at 5 is unmatched and resets the base; '(()())' at 6–11 is length 6. The two valid runs are separated by the unmatched ')', so they cannot be joined into 10. Counting matched pairs overall (5 pairs → 10) is the trap.

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

Exams that ask this topic