List Every Well-Formed Bracket Sequence in Dictionary Order
StringsAuto-graded · 15 test casesLast updated
Enumerate all well-formed bracket sequences using n pairs, returned in dictionary order, testing pruned backtracking and reasoning about output ordering.
You are given a positive integer n, the number of bracket pairs. Produce every well-formed bracket sequence that contains exactly n characters ( and exactly n characters ).
A sequence is well-formed if, when scanned from left to right, the running count of ) never goes above the running count of ( at any point, and both counts are equal once the whole sequence has been scanned.
Function
Implement balanced_strings(n), which returns a list of strings.
Rules
- Each returned string has length
2 * nand consists only of(and). - Every well-formed sequence appears in the result exactly once.
- The list must be in ascending dictionary order by character code. Since
(has code 40 and)has code 41,(is smaller than). This matches the ordering Python'ssorted()gives for these strings.
Constraints
1 <= n <= 8- For
n = 8the result has 1,430 strings.
Examples
Example 1
Input: balanced_strings(1)
Output: ['()']
Example 2
Input: balanced_strings(2)
Output: ['(())', '()()']
Example 3
Input: balanced_strings(3)
Output: ['((()))', '(()())', '(())()', '()(())', '()()()']
Hints
Hint 1
Build a sequence one character at a time, and only place a character if the partial sequence could still be completed into a well-formed one. Track how many `(` and how many `)` you have used.
Hint 2
A `(` is allowed while fewer than `n` have been used. A `)` is allowed only while the number of `)` used is smaller than the number of `(` used.
Hint 3
Think about which branch to explore first. If you always try `(` before `)`, the sequences come out already in dictionary order, so no sorting is needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use backtracking that constructs the sequence left to right, keeping two counters: open_used (number of ( placed) and close_used (number of ) placed). At each position there are at most two choices:
- Place
(ifopen_used < n. - Place
)ifclose_used < open_used.
When close_used == n, the sequence is complete (this forces open_used == n as well), so it is added to the result.
Always trying ( before ) means the search visits sequences in ascending dictionary order, so the output needs no sorting.
Why it is correct
- Only valid sequences are produced. The rule
close_used < open_usedkeeps every prefix valid, and the capopen_used < nbounds the number of(. Finishing atclose_used == nmeans both counts equaln. - All valid sequences are produced, once each. Every prefix of a well-formed sequence satisfies both rules, so the search can follow it character by character. Each leaf of the search tree corresponds to a distinct string.
- No dead ends. Any prefix with
close_used <= open_used <= ncan be finished by adding the remaining(and then the needed). Therefore every explored node leads to at least one result. - Sorted order. For two outputs, look at the first position where they differ. One has
(and the other). The(branch is fully explored before the)branch, so the smaller string is emitted first.
Complexity
The number of results is the Catalan number C(n) = (2n)! / ((n+1)! n!).
- Time: O(n * C(n)). Every node of the search tree lies on a path to a leaf, so there are at most 2n * C(n) nodes, and building each string costs O(n).
- Space: O(n) auxiliary (recursion depth and the shared buffer), plus O(n * C(n)) for the output.
Solution
from typing import List
def balanced_strings(n: int) -> List[str]:
result = []
path = []
def build(open_used, close_used):
if close_used == n:
result.append(''.join(path))
return
if open_used < n:
path.append('(')
build(open_used + 1, close_used)
path.pop()
if close_used < open_used:
path.append(')')
build(open_used, close_used + 1)
path.pop()
build(0, 0)
return result