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?
  1. A. 5
  2. B. 20
  3. C. 70
  4. 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

Exams that ask this topic