Skip to content

Commit 21d73b6

Browse files
authored
algorithm: unique paths (#1211)
* dp problem * update Directory.md * suggested changes
1 parent 16fa774 commit 21d73b6

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@
105105
* [RodCutting](Dynamic-Programming/RodCutting.js)
106106
* [Shuf](Dynamic-Programming/Shuf.js)
107107
* [SieveOfEratosthenes](Dynamic-Programming/SieveOfEratosthenes.js)
108+
* [UniquePaths](Dynamic-Programming/UniquePaths.js)
108109
* **Sliding-Window**
109110
* [LongestSubstringWithoutRepeatingCharacters](Dynamic-Programming/Sliding-Window/LongestSubstringWithoutRepeatingCharacters.js)
110111
* [PermutationinString](Dynamic-Programming/Sliding-Window/PermutationinString.js)

Dynamic-Programming/UniquePaths.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
/*
3+
*
4+
* Unique Paths
5+
*
6+
* There is a robot on an `m x n` grid.
7+
* The robot is initially located at the top-left corner.
8+
* The robot tries to move to the bottom-right corner.
9+
* The robot can only move either down or right at any point in time.
10+
*
11+
* Given the two integers `m` and `n`,
12+
* return the number of possible unique paths that the robot can take to reach the bottom-right corner.
13+
* More info: https://leetcode.com/problems/unique-paths/
14+
*/
15+
16+
/*
17+
* @param {number} m
18+
* @param {number} n
19+
* @return {number}
20+
*/
21+
22+
const uniquePaths = (m, n) => {
23+
// only one way to reach end
24+
if (m === 1 || n === 1) return 1
25+
26+
// build a linear grid of size m
27+
// base case, position 1 has only 1 move
28+
const paths = new Array(m).fill(1)
29+
30+
for (let i = 1; i < n; i++) {
31+
for (let j = 1; j < m; j++) {
32+
// paths[j] in RHS represents the cell value stored above the current cell
33+
// paths[j-1] in RHS represents the cell value stored to the left of the current cell
34+
// paths [j] on the LHS represents the number of distinct pathways to the cell (i,j)
35+
paths[j] = paths[j - 1] + paths[j]
36+
}
37+
}
38+
return paths[m - 1]
39+
}
40+
41+
export { uniquePaths }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { uniquePaths } from '../UniquePaths'
2+
3+
describe('Unique Paths', () => {
4+
it('should return 28 when m is 3 and n is 7', () => {
5+
expect(uniquePaths(3, 7)).toBe(28)
6+
})
7+
8+
it('should return 48620 when m is 10 and n is 10', () => {
9+
expect(uniquePaths(10, 10)).toBe(48620)
10+
})
11+
})

0 commit comments

Comments
 (0)