Tutorialspoint
Problem
Solution
Submissions

Unique Paths in a Grid

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

Write a JavaScript program to find the number of unique paths from the top-left corner to the bottom-right corner of a grid. You can only move either down or right at any point in time. Given a grid of size m × n, calculate the total number of possible unique paths from position (0,0) to position (m-1, n-1).

Example 1
  • Input: m = 3, n = 7
  • Output: 28
  • Explanation:
    • Grid size is 3×7, start at (0,0), target is (2,6).
    • At each cell, you can move right or down.
    • To reach (2,6), you need exactly 2 down moves and 6 right moves.
    • Total moves = 8, choose 2 positions for down moves.
    • Number of ways = C(8,2) = 8!/(2!×6!) = 28
Example 2
  • Input: m = 3, n = 2
  • Output: 3
  • Explanation:
    • Grid size is 3×2, start at (0,0), target is (2,1).
    • Path 1: Right → Down → Down.
    • Path 2: Down → Right → Down.
    • Path 3: Down → Down → Right.
    • Total unique paths = 3
Constraints
  • 1 ≤ m, n ≤ 100
  • You can only move right or down
  • Start position is always (0,0)
  • End position is always (m-1, n-1)
  • Time Complexity: O(m × n) for DP approach
  • Space Complexity: O(m × n) for DP table, can be optimized to O(n)
ArraysDynamic Programming PwCTutorix
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

  • Use dynamic programming to build up solutions from smaller subproblems
  • Create a 2D DP table where dp[i][j] represents paths to reach cell (i,j)
  • Initialize first row and first column to 1 (only one way to reach them)
  • For each cell, paths = paths from left + paths from above
  • Alternative: Use mathematical combination formula C(m+n-2, m-1)
  • Can optimize space by using only one row instead of full 2D table

Steps to solve by this approach:

 Step 1: Create a 2D DP table of size m × n initialized with zeros

 Step 2: Initialize the first row and first column to 1 (base cases)
 Step 3: Iterate through each cell starting from (1,1)
 Step 4: For each cell, calculate paths as sum of paths from left and above
 Step 5: Continue filling the entire DP table row by row
 Step 6: Return the value at the bottom-right corner dp[m-1][n-1]
 Step 7: Optional optimization: use single array instead of 2D table

Submitted Code :