Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(uniquepaths): add solution for unique paths problem #716

Merged
merged 5 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
})
}
}
Loading