Skip to content

Commit

Permalink
feat(uniquepaths): add solution for unique paths problem (#716)
Browse files Browse the repository at this point in the history
* feat(uniquepaths): add solution for unique paths problem

* fix: Remove extra unused memory
  • Loading branch information
rares985 authored May 11, 2024
1 parent 2354582 commit 2f8c738
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
31 changes: 31 additions & 0 deletions dynamic/uniquepaths.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// See https://leetcode.com/problems/unique-paths/
// author: Rares Mateizer (https://github.com/rares985)
package dynamic

// UniquePaths implements the solution to the "Unique Paths" problem
func UniquePaths(m, n int) int {
if m <= 0 || n <= 0 {
return 0
}

grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}

for i := 0; i < m; i++ {
grid[i][0] = 1
}

for j := 0; j < n; j++ {
grid[0][j] = 1
}

for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i-1][j] + grid[i][j-1]
}
}

return grid[m-1][n-1]
}
28 changes: 28 additions & 0 deletions dynamic/uniquepaths_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package dynamic

import (
"testing"
)

func TestUniquePaths(t *testing.T) {
testCases := map[string]struct {
m int
n int
want int
}{
"negative sizes": {-1, -1, 0},
"empty matrix both dimensions": {0, 0, 0},
"empty matrix one dimension": {0, 1, 0},
"one element": {1, 1, 1},
"small matrix": {2, 2, 2},
"stress test": {1000, 1000, 2874513998398909184},
}

for name, test := range testCases {
t.Run(name, func(t *testing.T) {
if got := UniquePaths(test.m, test.n); got != test.want {
t.Errorf("UniquePaths(%v, %v) = %v, want %v", test.m, test.n, got, test.want)
}
})
}
}

0 comments on commit 2f8c738

Please sign in to comment.