Generate Valid Parentheses
Generate all combinations of n pairs of well-formed parentheses. Uses backtracking with constraint that closing parentheses never exceed opening ones.
Visualization
Interactive visualization for Generate Valid Parentheses
Generate Valid Parentheses
• Backtracking with constraints
• close < open always
• Catalan number C(n) combinations
Interactive visualization with step-by-step execution
Implementation
1function generateParenthesis(n: number): string[] {
2 const result: string[] = [];
3
4 function backtrack(current: string, open: number, close: number): void {
5 if (current.length === 2 * n) {
6 result.push(current);
7 return;
8 }
9
10 if (open < n) {
11 backtrack(current + '(', open + 1, close);
12 }
13
14 if (close < open) {
15 backtrack(current + ')', open, close + 1);
16 }
17 }
18
19 backtrack('', 0, 0);
20 return result;
21}Deep Dive
Theoretical Foundation
Generate valid parentheses by maintaining invariant: at any point, number of closing parentheses ≤ opening parentheses. Total valid combinations = Catalan number C_n = (2n)!/(n!(n+1)!) ≈ 4^n/√(πn).
Complexity
Time
O(4^n / √n)
O(4^n / √n)
O(4^n / √n)
Space
O(n) recursion depth
Applications
Industry Use
Compiler design (expression parsing)
Mathematical expression validation
Code editor bracket matching
Parser generator tools
Syntax highlighting systems
Mathematical formula processors
Programming language interpreters
Use Cases
Related Algorithms
N-Queens Problem
The N-Queens Problem asks: place N chess queens on an N×N chessboard so that no two queens threaten each other. This means no two queens can be on the same row, column, or diagonal. It's a classic constraint satisfaction problem that demonstrates backtracking, pruning, and systematic exploration of solution spaces. The problem has applications in parallel processing, resource allocation, and algorithm design education.
Sudoku Solver
Sudoku Solver uses backtracking to fill a 9×9 grid with digits 1-9, ensuring each row, column, and 3×3 box contains all digits exactly once. This classic constraint satisfaction problem demonstrates systematic exploration with constraint checking. The algorithm fills empty cells one by one, backtracking when constraints are violated, making it a perfect example of pruning in search algorithms.
Combination Sum
Find all unique combinations in array where chosen numbers sum to target. Numbers can be reused. Classic backtracking problem with pruning optimization.
Word Search in Grid
Given 2D board and word, find if word exists in grid. Word must be constructed from letters of sequentially adjacent cells (horizontally or vertically). Uses backtracking with visited tracking.