Stack pattern

Longest Valid Parentheses

Given a string containing only the characters ( and ), return the length of the longest contiguous substring that forms a well-formed (properly matched) sequence of parentheses. Watch it run step by step, then write your own pseudocode and get it checked by AI.

  • LeetCode 32
  • Hard
  • 2 approaches

Sign in with Google or GitHub and you land straight on this page. DSA comes with the all labs plan and every ChaiCode batch.

StackLeetCode 32

Hard

From the first idea to the best one

  1. 01 Brute force · balance from every start O(n²)O(1) space
  2. 02 Optimized · index stack with base O(n)O(n) space
Each approach plays step by step, with its time and space.

What you will learn

  • How to read Longest Valid Parentheses and spot the stack pattern in it
  • Brute force · balance from every start: O(n²) time, O(1) space
  • Optimized · index stack with base: O(n) time, O(n) space
  • The pseudocode for each approach, its line lit as the animation runs
  • Practice: write your own pseudocode and get it checked

More Stack

See Longest Valid Parentheses run, step by step

Sign in and this page opens on the animation, with all 8 Stack problems beside it.

DSA comes with the all labs plan and every ChaiCode batch.