← Infosys bank

Infosys · Question 43 · Stacks

Longest Valid Parentheses

StacksC++code⏱ O(n)💾 O(n)
Service-based

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

  1. 1Push '(' indices; -1 bases the first run.
  2. 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.
yesno↻ repeatSTARTinclude <iostream>include <string>include <stack>include <algorithm>using namespace stdDEFINElongestValidParentheses(strings)stack<int> stst.push(-1)DEFINE maxLen = 0for (int i = 0; i <(int)s.size(); i++)if (s[i] == '(')st.push(i)} elseRETURN maxLenDEFINE main()cout <<longestValidParentheses(")()())")<< endlRETURN 0END
  • 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