-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(LeetCode #14): add Longest Common Prefix solution
- Loading branch information
Angelica Hjelm Gardner
committed
Nov 10, 2024
1 parent
9645b17
commit 515c09f
Showing
2 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} | ||
} |