Unique Paths II
Problem Statement
The same robot starts at the top-left cell of a grid and wants the bottom-right cell. It still moves only down or right. This time some cells hold an obstacle (value 1), and the robot cannot step on them. A free cell has value 0.
Return how many paths avoid every obstacle. If the start or the end cell is an obstacle, the answer is 0.
obstacleGrid, an m × n grid. 0 is a free cell and 1 is an obstacle.
The number of paths from the top-left cell to the bottom-right cell that never touch an obstacle.
The obstacle in the middle blocks every path through it. The two paths left are Right → Right → Down → Down and Down → Down → Right → Right.
Going right first runs into the obstacle, so the only path is Down → Right.
- • 1 ≤ m, n ≤ 100
- • Each cell is 0 or 1.
- • The tests are chosen so that the answer is at most 2 × 10^9.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Count the paths into a cell by adding the two cells that feed it; an obstacle counts as 0
dp[r][c] = 0 on an obstacle, otherwise dp above + dp left, with each cell worked out once
One row of counts: an obstacle sets row[c] = 0, and the flow from the left carries on from there
Let ways(r, c) be the number of obstacle-free paths from the top-left to (r, c). An obstacle has 0 paths. Any other cell is the cell above plus the cell to its left, and the start has 1 path. Start the recursion at the bottom-right corner.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Grid translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.