Skip to content
Next Next commit
Contribute: Added algorithm for Unique Paths problem
  • Loading branch information
Jaiharishan committed Oct 3, 2022
commit 781a7cff23db6e39251996abcf42ddf3d4231b4c
26 changes: 26 additions & 0 deletions Dynamic-Programming/UniquePaths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* A Dynamic Programming based solution for calculating the number ways to travel from Top-Left of the matrix to Bottom-Right of the matrix
* https://leetcode.com/problems/unique-paths/
*/

// Return the number of unique paths, given the dimensions of rows and columns

const uniquePaths = (rows, cols) => {
let dp = new Array(cols).fill(1)

for (let i = 1; i < rows; i++) {
const tmp = []

for (let j = 0; j < cols; j++) {
if (j === 0) {
tmp[j] = dp[j]
} else {
tmp[j] = tmp[j - 1] + dp[j]
}
}
dp = tmp
}
return dp.pop()
}

export { uniquePaths }
19 changes: 19 additions & 0 deletions Dynamic-Programming/tests/UniquePaths.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { uniquePaths } from '../UniquePaths'

test('Base Case 1', () => {
const rows = 3
const cols = 7
expect(uniquePaths(rows, cols)).toBe(28)
})

test('Base Case 2', () => {
const rows = 3
const cols = 2
expect(uniquePaths(rows, cols)).toBe(3)
})

test('Base Case 3', () => {
const rows = 8
const cols = 14
expect(uniquePaths(rows, cols)).toBe(77520)
})
18 changes: 6 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.