Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Stack

Longest Valid Parentheses

hard

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. A well-formed parentheses string is one that follows these rules:

  • Open brackets must be closed by a matching pair in the correct order.

For example, given the string "(()", the longest valid parentheses substring is "()", which has a length of 2. Another example is the string ")()())", where the longest valid parentheses substring is "()()", which has a length of 4.

Example 1:
Inputs:

s = "())))"

Output:

2

(Explanation: The longest valid parentheses substring is "()")

Example 2:
Inputs:

s = "((()()())"

Output:

8

(Explanation: The longest valid parentheses substring is "(()()())" with a length of 8)

Example 3:
Inputs:

s = ""

Output:

0

Explanation

At a high level, we can solve this problem by iterating over each index of the string, and then calculating the length of the longest valid parentheses substring that ends at that index. We can then take the maximum of these lengths to get the final answer.
Each time we encounter a closing parenthesis ')', it has the potential to close a valid parentheses substring. In order to calculate the length of the longest valid parentheses substring that ends at a given index, we need to know the index of the last unmatched opening parenthesis '('.
The length of the valid substring ending at the current index can be calculated by taking the difference between the current index and the index of the last unmatched opening parenthesis.
Let's visualize a few examples to understand how that calculation works:
(()201
Current index: 2. Last unmatched opening parenthesis at index 0. Length: 2 - 0 = 2
(()(3012
Current index: 3. Last unmatched opening parenthesis at index 1. Length: 3 - 1 = 2
(()(()301524
Current index: 5. Last unmatched opening parentheses = 1. Length = 5 - 1 = 4.
If there aren't any unmatched opening parentheses remaining after using the current closing parentheses, then we need to know the "start" of the current valid substring. Setting this value to -1 makes our calculation easier, as we can simply take the difference between the current index and the start of the valid substring to get the length.
())(3-1120
Current index: 3. The start of the current valid substring is -1, so length = 3 - (-1) = 4
However, if the closing parenthesis ')' doesn't close any valid substring (as shown below), then we can simply ignore it, and set the start of the current valid substring to the current index.
())) 3012
Current index: 3. But there is no unmatched opening parenthesis. Length: 0
This leads us to the following algorithm:
  1. Initialize a stack. The stack will always contain the index of the last unmatched opening parenthesis, or the "start" of the current valid substring. Initially, the stack will contain -1 as the start of the current valid substring.
  2. Each time we encounter an opening parenthesis '(', we'll push its index onto the stack, which represents the index of the last unmatched opening parenthesis.
  3. Each time we encounter a closing parenthesis ')', we'll do the following:
    1. We first pop the top element from the stack, as this closing parenthesis has the potential to close a valid parentheses substring.
    2. Now, after popping, there are two possible cases:
      1. The stack is not empty, and the top of the stack represents the index of the last unmatched opening parenthesis. We calculate the length of the valid substring ending at the current index by taking the difference between the current index and the index of the last unmatched opening parenthesis.
      2. The stack is empty. This means that this closing parenthesis was unmatched. We'll update the start of the valid substring to the current index by pushing the current index onto the stack.

Solution

Visualization
Python
Language
Try these examples:
def longest_valid_parentheses(s):
max_len = 0
stack = [-1]
for i, char in enumerate(s):
if char == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len
(()())

longest valid parentheses

0 / 17

Solution Visualization

Visualization
Python
Language
Try these examples:
def longest_valid_parentheses(s):
max_len = 0
stack = [-1]
for i, char in enumerate(s):
if char == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len
(()())

longest valid parentheses

0 / 17

Walkthrough

Example 1: s = "(()())"

Initialization

We initialize our stack with [-1] as a sentinel value representing the start of the current valid substring, and set max_len = 0.
Visualization
(()())

longest valid parentheses

0 / 0

Stack initialized with [-1], max_len = 0

Push opening parentheses at indices 0 and 1

We encounter '(' at indices 0 and 1. For each, we push the index onto the stack. The stack now holds [-1, 0, 1] — both indices are waiting to be matched.
Visualization
(()())max_len: 0i: 0-1stack

checking character '(' at index 0

0 / 2

Push indices 0 and 1 onto the stack

First match at index 2

We hit ')' at index 2. Pop index 1 from the stack — it's been matched. The top of the stack is now 0 (the last unmatched '('), so the valid substring length is 2 - 0 = 2. Update max_len = 2.
Visualization
(()())max_len: 0i: 2-101stack

checking character ')' at index 2

0 / 1

Pop index 1, calculate length: 2 - 0 = 2

Push at index 3, then match at index 4

Index 3 is '(' — push it. Index 4 is ')' — pop index 3. The top of the stack is still 0, so the valid substring length is 4 - 0 = 4. Update max_len = 4.
Visualization
(()())max_len: 2i: 3-10stack

checking character '(' at index 3

0 / 3

Push index 3, pop it at index 4. Length: 4 - 0 = 4

Final match at index 5

The last ')' at index 5 pops index 0. Now the top of the stack is -1 (our sentinel). The valid substring length is 5 - (-1) = 6 — the entire string is valid. Update max_len = 6.
Visualization
(()())max_len: 4i: 5-10stack

checking character ')' at index 5

0 / 1

Pop index 0, calculate length: 5 - (-1) = 6
We return max_len = 6.

Example 2: s = ")())()()"

Unmatched ) at index 0

After initializing the stack with [-1], we immediately hit ')'. We pop -1, but now the stack is empty — this means the ) was unmatched. We push index 0 onto the stack as the new "start" marker.
Visualization
)())()()

longest valid parentheses

0 / 3

Pop -1, stack empty → push index 0 as new start

Match () at indices 1–2

Push '(' at index 1. Then ')' at index 2 pops it. Top of stack is 0, so valid length is 2 - 0 = 2. Update max_len = 2.
Visualization
)())()()max_len: 0i: 10stack

checking character '(' at index 1

0 / 3

Push index 1, pop at index 2. Length: 2 - 0 = 2

Another unmatched ) at index 3

We hit ')' at index 3 and pop index 0. The stack is empty again — another unmatched ). Push index 3 as the new start marker. This resets where the next valid substring can begin.
Visualization
)())()()max_len: 2i: 30stack

checking character ')' at index 3

0 / 1

Pop index 0, stack empty → push index 3 as new start

Process ()() from indices 4–7

From index 4 onward, we process two consecutive pairs. Push 4, match at 5 (length 5 - 3 = 2). Push 6, match at 7 (length 7 - 3 = 4). Because both pairs are adjacent and share the same base marker at index 3, the length keeps growing. Update max_len = 4.
Visualization
)())()()max_len: 2i: 43stack

checking character '(' at index 4

0 / 8

Two consecutive matches extend from the same start. Length: 7 - 3 = 4
We return max_len = 4.
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n) where n is the length of the input string. We iterate over each character of the string once. At each character, we perform a constant amount of work.

Space Complexity: O(n) where n is the length of the input string. The stack can contain at most n elements (for example, if the input string is '(((((((((((').

Mark as read

Next: Monotonic Stack

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Solution

Solution Visualization

Walkthrough

Example 1: `s = "(()())"`

Example 2: `s = ")())()()"`

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress