Question presented to candidate: "A robot starts in the top-left corner of an m ร n grid and can only move right or down. How many different paths can it take to the bottom-right corner? After that, what changes if some cells are blocked? Please code it in Python."
What a strong answer should cover:
- The recurrence: a cell can only be entered from above or from the left, so
paths[r][c] = paths[r-1][c] + paths[r][c-1], with the whole first row and first column equal to 1. - O(mยทn) time; space from O(mยทn) down to O(n) by keeping a single row and updating it left to right.
- The closed form: every path is mโ1 downs and nโ1 rights in some order, so the answer is the binomial coefficient C(m+nโ2, mโ1), computable in O(min(m, n)) with exact integer steps.
- The obstacles variant: a blocked cell has 0 paths, and a blocked start or end makes the answer 0 โ the formula no longer applies, the DP does.
- Python details: build 2D tables with a comprehension, not
[[1] * n] * m(which shares one inner list),//for exact integer division, andmath.combfor the binomial โ with no overflow at any size.
Clarifying questions expected:
- Are the moves only right and down?
- How large can m and n be โ does the answer fit in 32 or 64 bits?
- Are there obstacles, and can the start or end cell itself be blocked?
Code / implementation expected: Yes โ a Python DP over the grid (one row of space is a plus); the binomial formula is a good follow-up.