VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-combinations-of-balanced-parentheses/

⇱ Print all combinations of balanced parentheses - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all combinations of balanced parentheses

Last Updated : 23 Jul, 2025

Given a number n, print all combinations of balanced parentheses of length n.

Note: A sequence of parentheses is balanced if every opening bracket ( has a corresponding closing bracket ) in the correct order.

Examples: 

Input: n = 2
Output: ["( )"]
Explanation: Only one valid sequence can be formed using 1 pair of parentheses, and it is balanced.

Input : n = 4
Output: [ "( ( ) )", "( )( )"]
Explanation: Two valid balanced sequences are possible with 2 pairs: one with nested parentheses, and one with pairs side by side.

[Naive Approach] Generating All Parentheses - O(2^n * n) Time and O(n) Space

The main idea is to generate all possible combinations of parentheses and check if it is balance or not. If a sequence is balanced, we store it as a valid result.

[Expected Approach] Using BackTracking

We recursively construct the sequence by considering these two conditions.

  • The i-th character can be '(' if the number of opening '(' brackets used so far is less than n. This ensures we don’t add more opening brackets than are needed, keeping the sequence valid.
  • The i-th character can be ')' if the number of closing ')' brackets used so far is less than the number of opening '(' brackets. This ensures that each closing bracket has a matching opening bracket before it, maintaining the balance.

Output
(())
()()

Time complexity: O(Cn​ × n), where Cn​ is the nth Catalan number.

  • Every valid sequence must start with an opening '('.
  • That '(' has to match some closing ')' later. Suppose it matches the very next character then you’ve enclosed 0 other pairs inside, and the rest of the string (after that match) is a valid sequence of n − 1 pairs.
  • Or, it might match after one full pair is inside—so you’ve enclosed 1 pair inside " (( … )) ", and the remainder after is a valid sequence of n−2 pairs.
  • Or you could enclose 2 pairs, 3 pairs, … up to n − 1 pairs.

If you let Ck​ be the number of sequences of k pairs, then for each choice of how many pairs you “enclose” inside the first match (call that k), you get

Ck ×  Cn−1−k

Summing over k = 0 to k = n-1 gives the Catalan recurrence

Cn = (k = 0 to n - 1) ∑ Ck ×  Cn−1−k

kRecurrenceValue
01
1C01
2C0C1 + C0C1 = 1+12
3C0C2 + C1C1 + C2C0 = 2+1+25
4 C0C3 + C1C2 + C2C1 + C3C0 = 5+2+2+514

Auxiliary space: O(n), for the recursion stack depth and the temporary string storing the current sequence.

Comment