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?- A. 14 ((())()) ()()()()
- B. 14 ((()())) ()()()()
- C. 16 ((())()) ()()()()
- 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
- Problem: Count the ways to place n queens on an n × n board so none attack each other. python def queens(n): cols, d1, d2 = set(), set()…
- Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell. python def…
- Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once). python def combo(k, s, n=9): out = []…
- Problem: The recursive function below counts calls. How many times is f called for f(5)? python calls = 0 def f(n): global calls calls +=…
- Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications. python mults = 0 def power(x, n): global mults…
- Problem: Generate the letter combinations a phone keypad number can represent and report how many there are. python from itertools import…