KatInterview

List Every Well-Formed Bracket Sequence in Dictionary Order

StringsAuto-graded · 15 test cases
MediumAuto-gradedStringsbacktrackingrecursioncombinatorics

Last 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 * n and 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's sorted() gives for these strings.

Constraints

  • 1 <= n <= 8
  • For n = 8 the 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.