InferenceAI

Enter at least two characters to search.

Start free

Balanced Bracket Strings

mediumRecursion & Backtracking25 min25 XP

Return every balanced string made of n pairs of ( and ), in lexicographic order (where ( comes before )).

The number of answers is the Catalan number Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n}.

Examples

EXAMPLE WALKTHROUGHfive strings

A guided view of the published example, not a trace of your code.

INPUT[3]
TASKbalanced_bracket_strings()
EXPECTED OUTPUT["((()))","(()())","(())()","()(())","()()()"]

Start with the input values shown in this example.

Example 1 of 3

Input: n = 3

Output: ["((()))","(()())","(())()","()(())","()()()"]

Explanation: five strings

Input: n = 1

Output: ["()"]

Explanation: one pair

Input: n = 0

Output: [""]

Explanation: zero pairs

Hint 1

Add '(' while you have some left; add ')' only while it would not exceed the opens so far.

Topics

DSARecursion & BacktrackingPython