Infosys · Question 43 · Stacks
Longest Valid Parentheses
Problem
Given a string containing '(' and ')', find length of the longest valid parentheses substring.
Approach
Use a stack of indices with -1 as the base. On ')', pop and measure to the new top.
Time O(n)Space O(n)
How it works
- 1Push '(' indices; -1 bases the first run.
- 2Each ')' pops; distance to the new top is valid length.
Sample input / output
Input: s = ")()())" Output: 4
Constraints
0 <= s.length <= 3 * 10^4; brackets only.
Solution — read it, then walk it
Time O(n)Space O(n)Loops 1Branches 1Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/18
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits