Skip to content

Commit

Permalink
feat(LeetCode #14): add Longest Common Prefix solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Angelica Hjelm Gardner committed Nov 10, 2024
1 parent 9645b17 commit 515c09f
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
29 changes: 29 additions & 0 deletions LeetCode/problem014_LongestCommonPrefix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Problem 14. Longest Common Prefix
*/

package leetcode

// Time complexity: O(n*m)
// Space complexity: O(1)
func longestCommonPrefix(strs []string) string {
// Edge case: if the input array is empty, return an empty string.
if len(strs) == 0 {
return ""
}

prefix := strs[0]

for _, s := range strs[1:] {
j := 0
for j < len(prefix) && j < len(s) && prefix[j] == s[j] {
j++
}
prefix = prefix[:j]
if prefix == "" {
return ""
}
}

return prefix
}
48 changes: 48 additions & 0 deletions LeetCode/problem014_LongestCommonPrefix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package leetcode

import (
"testing"
)

func TestLongestCommonPrefix(t *testing.T) {
var tests = []struct {
name string
input []string
output string
}{
{
name: "Example 1",
input: []string{"flower", "flow", "flight"},
output: "fl",
},
{
name: "Example 2",
input: []string{"dog", "racecar", "car"},
output: "",
},
{
name: "All strings identical",
input: []string{"test", "test", "test"},
output: "test",
},
{
name: "Single string in array",
input: []string{"single"},
output: "single",
},
{
name: "Empty array",
input: []string{},
output: "",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := longestCommonPrefix(tt.input)
if result != tt.output {
t.Errorf("longestCommonPrefix(%v) = %q; expected %q", tt.input, result, tt.output)
}
})
}
}

0 comments on commit 515c09f

Please sign in to comment.