DSA Stacks

Longest Valid Parentheses

Stack of indices anchored by the last invalid position; on each match, length = i - stack top.

Hard
Time O(n) Space O(n)
LeetCode
3 min read
stack dp

Problem#

Given a string of ( and ), return the length of the longest valid (well-formed) parentheses substring.

Examples#

  • "(()"2
  • ")()())"4
  • ""0

Constraints#

  • 0 <= s.length <= 3 * 10^4.

Approach#

Push indices of ( and unmatched ). Initialize the stack with -1 as a sentinel “last invalid index”. For (, push the index. For ), pop. If the stack is empty, push the current index as the new invalid anchor. Otherwise, the current valid length is i - stack.top().

Solution#

Longest Valid Parentheses
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int ans = 0;
for (int i = 0; i < (int)s.size(); ++i) {
if (s[i] == '(') st.push(i);
else {
st.pop();
if (st.empty()) st.push(i);
else ans = max(ans, i - st.top());
}
}
return ans;
}
};

Editorial#

The stack top always holds the index just before the current valid stretch starts. When we close a pair successfully, the length is i - newTop. Pushing -1 initially makes the math work for valid prefixes; pushing the unmatched ) index when the stack empties resets the anchor.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.