Leetcode #62 — a JavaScript Solution

This puzzle requires you to calculate the total number of unique paths from the top lefthand corner of a grid to the bottom righthand corner. You can only travel to the right or down, but may switch directions as much as you want.

Here’s one possible path for a 3 x 4 grid:

The grid above is has 10 possible solutions, and is simple enough that you can, with not too much trouble, imagine all 10 paths visually. However, as the grid expands, the permutations become much more difficult to keep track of.
A 5 x 5 grid has 70 possibilities!

Furthermore, mapping each of the possibilities to try to find doesn’t help. There is no good pattern evident for the sequence of paths.

The Solution

Aha moment! Instead of trying to keep track of the paths, we just need to determine how many different ways each square can be approached from and then add these totals for the next square of the grid.

Because we are moving from left to right and top to bottom, each of the edge squares ( the top row and the left hand column) need to be set to 1 (there is only one way to approach each of these squares.

The squares diagonally (down and to the right) are calculated by adding the left and upper adjacent squares until we reach the final square with the total number of possibilities!

In JavaScript we can accomplish this using a two dimensional array :[rows[columns]] to keep track of and reference the previous sums.

We create an array and initialize it with an inner array empty array which will contain the first row.

Next we fill the length of the first row with 1’s (our initial values).

Finally we iterate through the rest of the rows, adding an initial value of 1 for the first element (our left hand edge value), and then filling the next square with the sum of the value to the left and the value above until we reach the end, returning the last value of the array, our solution.

That’s it!

Written by

After years of teaching music in Austin, Shanghai and Yangon, I’m making a career change to my other passion, software development.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store