Data Structures & AlgorithmsVery hardCodeforces Div2 C/D · Amazon SDE OA
Count the lattice paths of length 8 with steps +1 and −1 that start at 0, never go below 0, and end at 0. Run the DP over positions and heights.
Count the lattice paths of length 8 with steps +1 and −1 that start at 0, never go below 0, and end at 0. Run the DP over positions and heights.
n=8
dp={0:1}
for _ in range(n):
nd={}
for h,v in dp.items():
for d in (1,-1):
if h+d>=0: nd[h+d]=nd.get(h+d,0)+v
dp=nd
print(dp.get(0,0))What is printed?- A. 5
- B. 20
- C. 70
- D. 14
Correct answer: D. 14
Nonnegative ±1 walks that return to 0 in 8 steps are counted by the Catalan number C4 = 14, which the height DP reproduces. Only 6 steps give C(6,3) = 20, dropping the nonnegativity constraint gives C(8,4) = 70, and forbidding touching 0 before the last step gives a different count.
More Coding Interview Problems questions
- How many ways are there to tile a 3 × 8 board completely with 1 × 2 dominoes (placed horizontally or vertically)? Count by DFS over the…
- Meetings are given as half-open intervals [(0,30),(5,10),(15,20),(12,25),(28,35)]. What is the minimum number of meeting rooms needed so…
- Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code. python a=list(range(1,15))…
- Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code…
- Problem: A connected undirected graph has 7 vertices. Its BFS tree from vertex 0 has depths: vertex 0 at depth 0, vertices 1 and 2 at…
- Problem: A graph's vertices 0–4 are connected by edges 0-1 (1), 1-2 (1), 2-3 (1), 3-4 (1), 0-4 (5), 1-3 (3). What is the largest…