Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth).

Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth).
def count(n, d):
    dp = [1] + [0] * d
    for _ in range(2 * n):
        nd = [0] * (d + 1)
        for k in range(d + 1):
            if dp[k]:
                if k < d: nd[k + 1] += dp[k]
                if k > 0: nd[k - 1] += dp[k]
        dp = nd
    return dp[0]
print(count(4, 2), count(4, 4))
What is printed?
  1. A. 14 14
  2. B. 4 8
  3. C. 1 14
  4. D. 8 14

Correct answer: D. 8 14

With no depth limit the count is the Catalan number C₄ = 14. With depth ≤ 2 every top-level block is '(' + a run of '()' + ')' or a bare '()', which gives 2ⁿ⁻¹ = 8 strings; the DP over (position, depth) confirms both.

More Coding Interview Problems questions

Exams that ask this topic