Skip to the solution
MediumDSA14 min read

How do you count unique paths in a grid?

624 views

The problem

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, and math.comb for 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.

  • dp
  • grid

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonUnique paths: 2D table, one row, and the binomial formula
PythonObstacles, and brute-force recursion vs DP call counts

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 77 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Decode ways DP: how do you handle 0 and 06 edge cases?

Continue