Unique Paths - 1D DP JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

We calculate the number of unique paths in an m × n grid from the top-left cell to the bottom-right cell using an optimized DP with O(n) space. The central idea is that to reach any cell, you can only come from the cell above it or the cell to its left — since movement is allowed only downward or rightward. Therefore, the total number of ways to reach a cell equals the sum of the ways to reach those two neighboring cells.

Because each cell depends on both its left neighbor (already updated for the current row) and its above neighbor (still stored from the previous row), the timing of updates aligns perfectly to allow using a single 1D array. As we move left to right, dp[col - 1] always contains the current row’s latest value, while dp[col] still represents the previous row’s value. This makes it possible to reuse one array without losing needed information.

  • State definition:
    Maintain a one-dimensional array dp of length n. dp[col] stores the number of ways to reach the cell in the current row at column col from the start cell (top-left).
  • Initialization:
    Set every entry of dp to 1. Each cell in the first row can be reached through exactly one unique path (moving only rightward), so the DP array starts as all ones.
  • Row processing (for each row rowIndex = 1 .. m-1):
    • The first cell (col = 0) can be reached through exactly 1 path (coming straight down), and this was also true for every previous row. Therefore, we skip recomputing col 0 and start updates from col 1.
    • For each column col = 1 .. n-1, we compute how many ways the cell can be reached:
      • From above — still stored in dp[col], since it hasn’t been overwritten yet for this row.
      • From the left — stored in dp[col - 1], which has already been updated for the current row.
      Then we update: dp[col] = dp[col] /* from above */ + dp[col - 1] /* from left */
  • Result:
    After all rows are processed, dp[n - 1] holds the total number of unique paths from top-left to bottom-right.

Time Complexity

The algorithm iterates through all m × n cells in the grid once, updating the DP array for each cell. Each update involves only constant-time operations, so the overall running time is O(m × n).

Space Complexity

The algorithm maintains a 1D DP array of size n and only a few scalar constants alongside it, which do not increase the overall space complexity. Therefore, the space complexity is O(n).

Visucodize editorial solution titled 1D DP JS Solution for LeetCode's Unique Paths coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/unique-paths.