Longest Valid Parentheses in Java (LeetCode 32): Stack Approach

Parentheses matching is a cornerstone category of coding interview problems. While basic problems like Valid Parentheses (LeetCode 20) only ask whether an entire sequence is balanced, LeetCode 32: Longest Valid Parentheses steps up the difficulty to Hard by asking for the length of the longest contiguous valid substring.

Let's break down the intuition behind tracking boundaries, explore why pushing -1 to the stack works so elegantly, and walk through a clean Java implementation.


1. Problem Statement

You are given a string s containing only the characters '(' and ')'. Your goal is to find the length of the longest valid (well-formed) parentheses substring.

Key Rules:
  • A substring must be contiguous (no skipping characters).
  • Every open bracket '(' must have a corresponding closing bracket ')' in the correct order.

Examples

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid substring is "()()".

Example 3:

Input: s = ""
Output: 0

2. Prefer Watching? Here is the Video Explanation


3. The Core Intuition: Tracking Indices Instead of Characters

A standard stack stores brackets ('(', ')'), but that only tells us if brackets match—it doesn't tell us where the match started or how long it is.

To compute lengths of contiguous substrings, we store indices in the stack instead of characters.

Why Push -1 Initially?

When calculating the length of a valid substring ending at index i, the formula is:

Length = i - stack.peek()

Consider the string "()":

  • At i = 0 ('('): We push 0. The stack holds [-1, 0].
  • At i = 1 (')'): We pop 0. The top of the stack is now -1.
  • Length: 1 - (-1) = 2.

Without -1 as the base boundary, the stack would become empty when matching the first pair, making it impossible to compute 1 - (-1) = 2 without extra conditional checks.

What Happens on an Unmatched ')'?

If we encounter a ')' and popping makes the stack completely empty, it means this ')' cannot be matched by any previous '('. It becomes the new baseline boundary for any future valid substrings, so we push its index onto the stack.


4. Interactive Visualization & Step-by-Step Dry Run

Test the stack execution interactively below. You can step forward and backward to see how indices are stored and measured:

Longest Valid Parentheses: watch the stack work
Type a string of ( and ) or pick an example, then click "Next step" to run your Java code one character at a time.
Examples:
Your own:
Input string s (with index numbers):
The stack (bottom on the left, top on the right). It stores indexes, not brackets:
Purple = the character being processed. Teal = the longest valid part found so far. Coral = a ")" that had no match, so it becomes the new base of the stack. The stack always keeps the index just before the current valid stretch, so the length is i - stack.peek().

Here is the table summarizing the dry run for s = ")()())":

Index (i) Char Action Stack Contents Length Calculated Max Length
Start — Push base index -1 [-1] — 0
0 ) Pop -1 → Stack empty → Push 0 [0] Boundary reset 0
1 ( Push index 1 [0, 1] — 0
2 ) Pop 1 → Stack top is 0 [0] 2 - 0 = 2 2
3 ( Push index 3 [0, 3] — 2
4 ) Pop 3 → Stack top is 0 [0] 4 - 0 = 4 4
5 ) Pop 0 → Stack empty → Push 5 [5] Boundary reset 4

Final Output: 4 (representing the substring "()()" between index 1 and 4).


5. Java Implementation

import java.util.Stack;

class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<>();

        // Base boundary index to handle substrings starting at index 0
        stack.push(-1);
        int max = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                // Push index of open bracket
                stack.push(i);
            } else {
                // Pop the matching '(' or previous boundary
                stack.pop();

                if (stack.isEmpty()) {
                    // Current ')' has no matching '('; it becomes the new boundary
                    stack.push(i);
                } else {
                    // Valid substring found between stack.peek() and current index i
                    int length = i - stack.peek();
                    max = Math.max(max, length);
                }
            }
        }

        return max;
    }
}

6. Complexity Analysis

  • Time Complexity: O(n)
    We iterate through the string of length n exactly once. Each character index is pushed and popped at most once, which runs in O(1) amortized time.
  • Space Complexity: O(n)
    In the worst case (e.g., all open brackets "((((("), the stack will store up to n + 1 elements.

7. Key Takeaways & Interview Tips

  • Store indices, not characters: When an interview question asks for the length or span of valid parenthetical structures, storing indices in the stack is nearly always the solution.
  • Boundary Sentinel: Starting the stack with -1 removes the need for special branch conditions for valid substrings starting at index 0.
  • Boundary Reset: Unmatched closing brackets act as dividers. Resetting the stack top to that index preserves valid boundary calculation for future pairs.

Comments

Popular posts from this blog

Climbing Stairs in Java (LeetCode 70): DP Approach

Unique Paths in Java (LeetCode 62): DP Approach