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?- A. 14 14
- B. 4 8
- C. 1 14
- 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
- Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight). python from functools import…
- Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs. python cost = [[9, 2, 7…
- Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP. python from collections…
- Edge case: greedy coin change versus DP when the coin system is not canonical. python def greedy(coins, x): cnt = 0 for c in sorted(coins…
- Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters). python def ways(n): dp = [1] + [0] n for i in…
- Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity. python def frac(items…