Generate parentheses
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Generating parentheses means listing every valid way to write a given number of bracket pairs so each opening bracket is closed properly. The trick is to only add a closing bracket when something is still open. It teaches you to build answers step by step and refuse invalid steps early.
Practical use cases
- Web app: Testing a JSON or formula validator. You built a form field where users type a formula like (a+(b*c)). To test the bracket checker, you need many valid and tricky inputs. Generating all valid bracket patterns for 1 to 4 pairs gives 1, 2, 5 and 14 patterns, and the test suite can feed each to the validator to make sure none are wrongly rejected.
- Web app: Code editor auto-closing brackets. A browser-based code editor must decide when typing a closing bracket is legal and when to auto-insert one. The same rule applies: you may close only if more brackets are open than closed. Knowing this makes the logic for highlighting mismatched brackets short and bug-free. Without it, the editor would show red error marks on perfectly good code and users would stop trusting it.
- System: Compilers and parsers. A compiler reading source code or an HTML parser reading tags must confirm everything opened gets closed in the right order. Generating valid patterns is the mirror image of checking them, and the same rule underlies both. Whenever you meet the word nested in a spec, such as XML, JSON or HTML, this same open-before-close rule is quietly at work behind the scenes.
The story: The Door Bell Brackets
Grandpa Bhaskar loved word games. One evening he challenged Mira: "Write every way to place three pairs of brackets so each opening bracket gets closed properly." Mira wrote ((())) proudly. Then she tried ())(() and Grandpa tutted: "That closes a door that was never opened!"
Mira could have written all 64 strings of six brackets and thrown out the bad ones. But Kabir had a smarter idea: never write a bad bracket in the first place. "You may add an opening bracket if you still have some left. You may add a closing bracket only if there is an open one waiting."
With those two rules Mira simply walked: open, open, open, then she had to close three times. Back up, and where she could, she closed earlier and opened again: (()()), (())(), ()(()), ()()().
Five strings, all correct, no wrong ones ever written. Grandpa clapped. This is the power of backtracking: prune a branch the moment it breaks a rule.
How to spot this problem, and where you need it
You must produce or verify strings of brackets, tags or nested blocks where every opener needs a matching closer, and you cannot afford to build thousands of invalid ones first.
Signs you need it
- The problem says "well-formed", "balanced" or "valid" brackets and asks for all of them for a given count.
- Trying all possible strings of ( and ) and filtering gives millions of mostly invalid strings, so it is far too slow.
- Your data has nesting, like menus inside menus or tags inside tags, and order of closing matters.
Where to use it in a project
- Generating test cases for a parser, template engine or formula validator.
- Building nested structures such as category trees or comment threads in a way that never leaves anything unclosed.
The solution
Build the string one character at a time, tracking how many openers and closers you have used. You may add an opener if you have not used all of them. You may add a closer only if more are open than closed. When the string reaches full length, it is guaranteed valid, so save it. Because invalid choices are never made, no time is wasted on bad strings, and stepping back to try the other choice is backtracking.
Payoff: Before: checking 256 strings to find the 14 valid ones for 4 pairs. After: only the 14 valid ones are ever built.
Explain it like I am 8
You have 3 doors to open and 3 to close. You can only close a door you already opened. Walk step by step: open a door if you still have doors to open, or close a door if one is waiting. Every full walk that ends with everything closed is a correct answer.
How it works, step by step
- Track how many opens and closes are used so far, and the string built.
- Base case: when the string has
2 × ncharacters, it is complete and valid, so save it. - Choose "(" if opens used is less than n, then explore.
- Choose ")" only if closes used is less than opens used, then explore.
- Because we pass new strings down (no shared state), there is nothing extra to undo here. The "un-choose" happens by returning.
The code in four languages
PHP
<?php
// All well-formed strings made from $n pairs of round brackets.
function generateParentheses(int $n): array {
$result = [];
$build = function (string $s, int $open, int $close) use (&$build, &$result, $n) {
if (strlen($s) === 2 * $n) { // base case: complete and valid
$result[] = $s;
return;
}
if ($open < $n) { // we still have an opening bracket to place
$build($s . '(', $open + 1, $close);
}
if ($close < $open) { // only close something that is open
$build($s . ')', $open, $close + 1);
}
};
$build('', 0, 0);
return $result;
}
print_r(generateParentheses(3));JavaScript
// All well-formed strings made from n pairs of round brackets.
function generateParentheses(n) {
const result = [];
function build(s, open, close) {
if (s.length === 2 * n) { // base case: complete and valid
result.push(s);
return;
}
if (open < n) { // we still have an opening bracket to place
build(s + '(', open + 1, close);
}
if (close < open) { // only close something that is open
build(s + ')', open, close + 1);
}
}
build('', 0, 0);
return result;
}
console.log(generateParentheses(3));Java
import java.util.*;
public class Main {
// All well-formed strings made from n pairs of round brackets.
static List<String> generateParentheses(int n) {
List<String> result = new ArrayList<>();
build("", 0, 0, n, result);
return result;
}
static void build(String s, int open, int close, int n, List<String> result) {
if (s.length() == 2 * n) { // base case: complete and valid
result.add(s);
return;
}
if (open < n) { // we still have an opening bracket to place
build(s + "(", open + 1, close, n, result);
}
if (close < open) { // only close something that is open
build(s + ")", open, close + 1, n, result);
}
}
public static void main(String[] args) {
System.out.println(generateParentheses(3)); // [((())), (()()), (())(), ()(()), ()()()]
}
}Go
package main
import "fmt"
// generateParentheses returns all well-formed strings made from n pairs of round brackets.
func generateParentheses(n int) []string {
var result []string
var build func(s string, open, close int)
build = func(s string, open, close int) {
if len(s) == 2*n { // base case: complete and valid
result = append(result, s)
return
}
if open < n { // we still have an opening bracket to place
build(s+"(", open+1, close)
}
if close < open { // only close something that is open
build(s+")", open, close+1)
}
}
build("", 0, 0)
return result
}
func main() {
fmt.Println(generateParentheses(3)) // [((())) (()()) (())() ()(()) ()()()]
}Time: O(4^n) · Extra space: O(n). The count of answers grows roughly four times per extra pair (it is called the Catalan number). Pruning means every branch we build can lead to a valid answer.
Watch out for
- Allowing ")" whenever there are closes left (
close < n). That creates strings like())((). The right test isclose < open. - Generating all 2^(2n) strings and filtering at the end. It works but wastes a lot of time.
- Mutating a shared string and forgetting to undo. Passing a new string avoids that.
Quick check
- When may you add a ")"?
- Always
- Only at the end
- When opens used equals n
- When closes used is less than opens used
- How many valid strings for n = 3?
- 5
- 3
- 6
- 8
- Why is this better than building all strings then checking?
- It prunes bad branches early
- It uses no recursion
- It sorts the answers