Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first).

Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first).
def gen(n):
    out = []
    def bt(s, o, c):
        if len(s) == 2 * n: out.append(s); return
        if o < n: bt(s + '(', o + 1, c)
        if c < o: bt(s + ')', o, c + 1)
    bt('', 0, 0)
    return out
r = gen(4)
print(len(r), r[2], r[-1])
What is printed?
  1. A. 14 ((())()) ()()()()
  2. B. 14 ((()())) ()()()()
  3. C. 16 ((())()) ()()()()
  4. D. 14 ((()))() ()()()()

Correct answer: A. 14 ((())()) ()()()()

Add '(' while fewer than n are open; add ')' only when it closes an open one. The count is Catalan(4) = 14 (not 2⁴ = 16). With '(' tried first the order starts (((()))), ((()())), ((())()), ((()))(), … so r[2] = ((())()), and the last string is ()()()(). Output-sensitive O(4ⁿ/√n).

More Coding Interview Problems questions

Exams that ask this topic