#104 · Recursion and backtracking · Intermediate · 85 XP · about 15 min
A string of round brackets is balanced when every ( is closed by a later ) and no ) closes something that was never opened. Write balanced_strings(n) that returns every balanced string made of exactly n opening and n closing brackets, as a sorted list.
balanced_strings(1) # returns ['()'] balanced_strings(2) # returns ['(())', '()()'] balanced_strings(3) # returns ['((()))', '(()())', '(())()', '()(())', '()()()']
0 <= n <= 10For n = 0 there is exactly one balanced string, the empty string, so the answer is ['']. The count grows fast: there are 16,796 strings for n = 10.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.