00:00

Problem Statement

Input/Output Examples

Visual Explanation

When a ) pops a matching (, the valid run ends at i and starts right after the index now on top of the stack. That is why the stack starts with -1.

Approaches

The stack solution is easy to reason about. The two-pass counter solution reaches the same answer with constant memory.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. The stack version reads each character once and may store up to n indexes; the counter version reads the string twice with two integers.

Interview Tips and Recommended Approach

  • Explain the -1 base. It lets the first valid run, starting at index 0, be measured with the same formula.
  • Do not just count pairs. The pairs must form one contiguous run, as "()(()" shows.
  • Know why two passes are needed for the counter method: each direction misses one kind of imbalance.
  • Mention the DP alternative. dp[i], the longest valid run ending at i, also works in O(n).

Recommended Approach: Stack of Indexes

Why: the index stack makes the start of each valid run explicit, so the length formula is easy to justify, and it needs only one pass.