Tutorialspoint
Problem
Solution
Submissions

Unique Paths in a Grid

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to find the number of unique paths from the top-left corner to the bottom-right corner of an m×n grid. You can only move either down or right at any point in time.

Example 1
  • Input: m = 3, n = 2
  • Output: 3
  • Explanation:
    • Step 1: In a 3×2 grid, we need to go from (0,0) to (2,1).
    • Step 2: The possible paths are:
      • Right → Right → Down
      • Right → Down → Right
      • Down → Right → Right
    • Step 3: Therefore, there are 3 unique paths.
Example 2
  • Input: m = 7, n = 3
  • Output: 28
  • Explanation:
    • Step 1: In a 7×3 grid, we need to go from (0,0) to (6,2).
    • Step 2: We need to make exactly 6 right moves and 2 down moves.
    • Step 3: The number of ways to arrange these moves is given by the combination formula C(8,2) = 28.
    • Step 4: Therefore, there are 28 unique paths.
Constraints
  • 1 <= m, n <= 100
  • The answer will be less than or equal to 2 * 10^9
  • Time Complexity: O(m*n)
  • Space Complexity: O(m*n) or O(min(m,n))
ArraysHCL TechnologiesPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • This is a classic dynamic programming problem.
  • Create a 2D array to store the number of ways to reach each cell.
  • The number of ways to reach a cell is the sum of ways to reach the cell above it and the cell to its left.
  • Base case: There is exactly 1 way to reach any cell in the first row or first column.
  • Build the solution bottom-up and return the value at the bottom-right cell.

Steps to solve by this approach:

 Step 1: Create a 2D array dp[m][n] to store the number of unique paths to each cell.

 Step 2: Initialize the first row and first column of the dp array to 1, as there is only one way to reach any cell in the first row or column (by moving only right or only down).
 Step 3: For each cell (i,j) starting from (1,1), the number of ways to reach it is the sum of ways to reach the cell above it (i-1,j) and the cell to its left (i,j-1).
 Step 4: Fill the dp array using the recurrence relation: dp[i][j] = dp[i-1][j] + dp[i][j-1].
 Step 5: Return dp[m-1][n-1], which contains the number of unique paths to the bottom-right corner.

Submitted Code :