1. Full length
A valid string uses n open and n close brackets, so length is 2n.
if (path.length === n * 2)Typorithm · medium
Step 1 of 8 · intro card
Backtracking
Build only valid bracket strings by adding an open while open < n and a close while close < open.
Instead of generating all strings and filtering, the constraints prune invalid branches up front.
You may add an open bracket whenever fewer than n are used, and a close bracket only when it has a matching open.
These two rules guarantee every produced string is already balanced.
Open while open < n.
Close while close < open.
Length 2n means a complete string.
function generateParenthesis(n) {
const result = [];
const path = [];
function backtrack(open, close) {
if (path.length === n * 2) {
result.push(path.join(""));
return;
}
if (open < n) {
path.push("(");
backtrack(open + 1, close);
path.pop();
}
if (close < open) {
path.push(")");
backtrack(open, close + 1);
path.pop();
}
}
backtrack(0, 0);
return result;
}Connect each part of the code to the concept before you type.
A valid string uses n open and n close brackets, so length is 2n.
if (path.length === n * 2)Add an open bracket only while fewer than n have been used.
if (open < n)Add a close bracket only when an unmatched open exists.
if (close < open)Remove the bracket to try the alternative branch.
path.pop()Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputPairs n = 3
∅ Empty state
Follow temporary values, local state and supporting structures at this step.
Live recursive calls, including their arguments. Returning releases the top frame.
Current choice path0 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state