Grid unique paths

Dynamic Programming DP on grids Medium
  • This type of problem corresponds to a well-known algorithmic concept used in pathfinding - giving rise to techniques like Dijkstra's or A* algorithms
  • These are extensively used in the software industry, notably in GPS software for finding shortest routes, in game development for enabling characters to navigate through a game map, or in logistics and supply chain softwares for optimizing routes
  • Specifically, such a "unique ways" problem introduces the concepts of grid-based pathfinding and combinatorial counting, foundational for these advanced navigational systems

Given two integers m and n, representing the number of rows and columns of a 2d array named matrix. Return the number of unique ways to go from the top-left cell (matrix[0][0]) to the bottom-right cell (matrix[m-1][n-1]).


 Movement is allowed only in two directions from a cell: right and bottom.

Examples:

Input: m = 3, n = 2

Output: 3

Explanation: There are 3 unique ways to go from the top left to the bottom right cell.

1) right -> down -> down

2) down -> right -> down

3) down -> down -> right

Input: m = 2, n = 4

Output: 4

Explanation: There are 4 unique ways to go from the top left to the bottom right cell.

1) down -> right -> right -> right

2) right -> down -> right -> right

3) right -> right -> down -> right

4) right -> right -> right -> down

Input: m = 3, n = 3

Constraints

  • 1 <= n, m <= 100
  • The answer will not exceed 109

Hints

  • "The number of ways to reach a cell depends on how you got there: From the left (matrix[i][j-1]) From the top (matrix[i-1][j])"
  • "A recursive approach without memoization results in exponential time complexity (O(2^{m+n})), making it inefficient for large grids. Using dynamic programming (O(m*n)), we store results in a dp[][] table to avoid redundant calculations."

Company Tags

Visa Dropbox Cloudflare Electronic Arts Twilio eBay Teladoc Health Ubisoft DoorDash Johnson & Johnson Seagate Technology American Express Airbnb AMD Flipkart Pinterest Optum Uber Instacart Target Epic Systems JPMorgan Chase Ernst & Young PwC Chewy Google Microsoft Amazon Meta Apple Netflix Adobe