Java String Program · S42
Generate Parentheses in Java
List every well-formed string of n pairs of parentheses. Backtracking adds a bracket only when the result can still become valid, so no invalid string is ever built.
Problem Statement
Given n, return every string of n opening and n closing parentheses in which every closing parenthesis matches an earlier opening one.
Return the strings in lexicographic order, where ( comes before ).
Input/Output Examples
n = 1Output[()] (1)Explanation: only one arrangement is possible.n = 2Output[(()), ()()] (2)Explanation: nested or side by side.n = 3Output[((())), (()()), (())(), ()(()), ()()()] (5)Explanation: the counts 1, 2, 5, 14, … are the Catalan numbers.Visual Explanation
- Startcurrent(open 1, close 0 only ( is allowed
- Branchcurrent((or()open < n → (, close < open → )
- Leavesn = 2(())()()length 2n reached
- Done2 strings
n = 2: ( may be added while fewer than n are open, and ) only while it closes an open one, so every leaf is valid.The two rules prune every branch that would produce an invalid string. As a result, the work done is proportional to the number of valid answers, not to all 22n bracket strings.
Approaches
Backtracking builds strings character by character. The dynamic-programming approach builds them from smaller answers.
Approach 1: Backtracking With Counts (Recommended)
Idea: track how many ( and ) have been used, and add each bracket only when the string can still become valid.
- If the string has length
2n, record it. - If
open < n, add(, recurse and remove it. - If
close < open, add), recurse and remove it.
Time: O(4n / √n) · Space: O(n). Space excludes the output; the recursion depth is 2n.
Approach 2: Build From Smaller Answers
Idea: every valid string can be written as (A)B, where A has i pairs and B has the remaining n - 1 - i pairs.
- Start with
dp[0] = [""]. - For each size, combine every
Afromdp[i]with everyBfromdp[size - 1 - i]. - Sort
dp[n]to match the backtracking order.
Time: O(4n / √n) · Space: O(4n / √n).
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: Backtracking With Counts (Recommended)
Trying ( before ) produces the results in lexicographic order automatically.
import java.util.ArrayList;
import java.util.List;
public class ParenthesesBacktrack {
// Add '(' while some are left; add ')' only when it closes an open '('
static List<String> generate(int n) {
List<String> result = new ArrayList<>();
build(n, 0, 0, new StringBuilder(), result);
return result;
}
private static void build(int n, int open, int close, StringBuilder current, List<String> result) {
if (current.length() == 2 * n) {
result.add(current.toString());
return;
}
if (open < n) {
current.append('(');
build(n, open + 1, close, current, result);
current.deleteCharAt(current.length() - 1);
}
if (close < open) {
current.append(')');
build(n, open, close + 1, current, result);
current.deleteCharAt(current.length() - 1);
}
}
public static void main(String[] args) {
for (int n = 1; n <= 3; n++) {
List<String> r = generate(n);
System.out.println("n=" + n + " -> " + r + " (" + r.size() + ")");
}
}
}
n=1 -> [()] (1) n=2 -> [(()), ()()] (2) n=3 -> [((())), (()()), (())(), ()(()), ()()()] (5)
Time complexity: O(4n / √n) · Space complexity: O(n).
Approach 2: Build From Smaller Answers
Shows where the Catalan recurrence comes from, but it keeps every smaller list in memory.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ParenthesesDp {
// Every valid string is "(" + A + ")" + B, where A has i pairs and B has n - 1 - i pairs
static List<String> generate(int n) {
List<List<String>> dp = new ArrayList<>();
dp.add(List.of(""));
for (int pairs = 1; pairs <= n; pairs++) {
List<String> current = new ArrayList<>();
for (int i = 0; i < pairs; i++) {
for (String inside : dp.get(i)) {
for (String after : dp.get(pairs - 1 - i)) {
current.add("(" + inside + ")" + after);
}
}
}
dp.add(current);
}
List<String> result = new ArrayList<>(dp.get(n));
Collections.sort(result); // same order as the backtracking version
return result;
}
public static void main(String[] args) {
for (int n = 1; n <= 3; n++) {
List<String> r = generate(n);
System.out.println("n=" + n + " -> " + r + " (" + r.size() + ")");
}
}
}
n=1 -> [()] (1) n=2 -> [(()), ()()] (2) n=3 -> [((())), (()()), (())(), ()(()), ()()()] (5)
Time complexity: O(4n / √n) · Space complexity: O(4n / √n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Backtracking With Counts | O(4n / √n) | O(n) |
| Build From Smaller Answers | O(4n / √n) | O(4n / √n) |
The number of valid strings is the n-th Catalan number, about 4n / (n √n), and each has length 2n. Any correct solution must produce all of them.
Interview Tips and Recommended Approach
- State the two rules.
open < nto add(;close < opento add). - Avoid generate-then-filter. Building all
22nstrings and checking each wastes work on invalid ones. - Mention the Catalan numbers. 1, 1, 2, 5, 14, 42, … is a strong signal you understand the structure.
- Reuse one builder. Appending and deleting on a shared
StringBuilderkeeps memory atO(n).
Recommended Approach: Backtracking With Counts
Why: it never creates an invalid string, keeps only the current path in memory and produces the results already sorted.