Math Fundamentals18 sections · 814 units
Open in Course

Unique Paths - Implementation

(2D DP table)

Here's the full solution:


function uniquePaths(m, n)
    dp := 2D array of size m × n
    // Initialize first row and column
    for i from 0 to m - 1
        dp[i][0] := 1
    for j from 0 to n - 1
        dp[0][j] := 1
    // Fill the rest
    for i from 1 to m - 1
        for j from 1 to n - 1
            dp[i][j] := dp[i - 1][j] + dp[i][j - 1]
    return dp[m - 1][n - 1]

You build up the table row by row. Each cell gets the sum of paths from above and from the left. Time: O(m×n)O(m \times n), Space: O(m×n)O(m \times n).