Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Paths around obstacles

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazonGoogle

A grid holds 0 for an open cell and 1 for an obstacle. Moving only right or down, count the paths from the top-left cell to the bottom-right cell that never enter an obstacle. If either corner is an obstacle, the answer is 0.

Examples

InputOutputWhy
grid = [[0,0,0],[0,1,0],[0,0,0]]2Around the obstacle on either side.
grid = [[0,1],[0,0]]1Down, then right.
grid = [[1]]0The start is blocked.

Constraints

  • 1 ≤ rows, cols ≤ 100
  • The answer fits in a 32-bit integer

Hints

Hint 1

ways[r][c] = ways[r − 1][c] + ways[r][c − 1] for an open cell, 0 for an obstacle.

Hint 2

The start has one way if it is open.

Hint 3

A single row: ways[c] += ways[c − 1], reset to 0 at obstacles.

Where people lose marks

  • Initialising the whole first row and column to 1, which ignores obstacles part-way along them.
  • Forgetting that a blocked start or end gives 0.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.