Typorithm · medium

Generate Parentheses

▷ Interactive algorithm labgenerate-parenthesesbacktrackingconstraintsopen-close-countschoose-explore-undo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Generate Parentheses

0%

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.

Preparing algorithm lab…
01

Open while open < n.

02

Close while close < open.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Full length

A valid string uses n open and n close brackets, so length is 2n.

if (path.length === n * 2)

2. Can open

Add an open bracket only while fewer than n have been used.

if (open < n)

3. Can close

Add a close bracket only when an unmatched open exists.

if (close < open)

4. Undo

Remove the bracket to try the alternative branch.

path.pop()

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Generate Parentheses: Visual Walkthrough & Practice · Typorithm | ApplyDjinn