Java String Program · S61
Longest Valid Parentheses in Java
Find the longest contiguous run of brackets that is correctly balanced. A stack of indexes remembers where the current valid run started.
Problem Statement
Given a string containing only ( and ), return the length of the longest substring that is a well-formed parentheses sequence.
If no such substring exists, return 0.
Input/Output Examples
"())(())"Output4Explanation: the unmatched ) splits the string; "(())" is the longer valid part."(()"Output2Explanation: only "()" is valid."()(()"Output2Explanation: the second ( is never closed, so the runs cannot join.Visual Explanation
- i = 0, 1stack-1push 0, pop it length 1 − (−1) = 2
- i = 2stack2extra ): new base 2 run restarts
- i = 3–6stack2(()) pairs up length 6 − 2 = 4
- Done4
"())(())": the bottom of the stack is the index just before the current valid run. The unmatched ) at index 2 becomes the new base (amber).When a ) pops a matching (, the valid run ends at i and starts right after the index now on top of the stack. That is why the stack starts with -1.
Approaches
The stack solution is easy to reason about. The two-pass counter solution reaches the same answer with constant memory.
Approach 1: Stack of Indexes (Recommended)
Idea: push the index of every (; on ), pop and measure the run from the new top of the stack.
- Start with
-1on the stack as a base. - On
(, push its index. - On
), pop; if the stack is now empty, pushias the new base; otherwise, the run length isi - stack.peek().
Time: O(n) · Space: O(n).
Approach 2: Two-Pass Counters
Idea: scan left to right counting opens and closes, resetting when closes exceed opens; then scan right to left with the opposite rule.
- Left to right: when
open == close, record2 × close; whenclose > open, reset both. - Right to left: when
open == close, record2 × open; whenopen > close, reset both. - Return the best value.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Stack of Indexes (Recommended)
The base index handles both the start of the string and every unmatched ).
import java.util.ArrayDeque;
import java.util.Deque;
public class ValidParensStack {
// The stack holds indexes; its bottom is the index just before the current valid run
static int longestValid(String s) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(-1);
int best = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i); // unmatched ')': new base
} else {
best = Math.max(best, i - stack.peek());
}
}
}
return best;
}
public static void main(String[] args) {
String[] inputs = {"())(())", "(()", "()(()", ""};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + longestValid(s));
}
}
}
"())(())" -> 4 "(()" -> 2 "()(()" -> 2 "" -> 0
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Two-Pass Counters
The second pass is needed for strings like "(()", where the first pass never sees equal counts.
public class ValidParensCounters {
// Two scans with open/close counters; no stack needed
static int longestValid(String s) {
int best = 0;
int open = 0;
int close = 0;
for (int i = 0; i < s.length(); i++) { // left to right: too many ')' resets
if (s.charAt(i) == '(') {
open++;
} else {
close++;
}
if (open == close) {
best = Math.max(best, 2 * close);
} else if (close > open) {
open = 0;
close = 0;
}
}
open = 0;
close = 0;
for (int i = s.length() - 1; i >= 0; i--) { // right to left: too many '(' resets
if (s.charAt(i) == '(') {
open++;
} else {
close++;
}
if (open == close) {
best = Math.max(best, 2 * open);
} else if (open > close) {
open = 0;
close = 0;
}
}
return best;
}
public static void main(String[] args) {
String[] inputs = {"())(())", "(()", "()(()", ""};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + longestValid(s));
}
}
}
"())(())" -> 4 "(()" -> 2 "()(()" -> 2 "" -> 0
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Stack of Indexes | O(n) | O(n) |
| Two-Pass Counters | O(n) | O(1) |
Here n is the length of the string. The stack version reads each character once and may store up to n indexes; the counter version reads the string twice with two integers.
Interview Tips and Recommended Approach
- Explain the
-1base. It lets the first valid run, starting at index 0, be measured with the same formula. - Do not just count pairs. The pairs must form one contiguous run, as
"()(()"shows. - Know why two passes are needed for the counter method: each direction misses one kind of imbalance.
- Mention the DP alternative.
dp[i], the longest valid run ending ati, also works inO(n).
Recommended Approach: Stack of Indexes
Why: the index stack makes the start of each valid run explicit, so the length formula is easy to justify, and it needs only one pass.