diff --git a/LeetCode/problem014_LongestCommonPrefix.go b/LeetCode/problem014_LongestCommonPrefix.go new file mode 100644 index 0000000..47a8936 --- /dev/null +++ b/LeetCode/problem014_LongestCommonPrefix.go @@ -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 +} diff --git a/LeetCode/problem014_LongestCommonPrefix_test.go b/LeetCode/problem014_LongestCommonPrefix_test.go new file mode 100644 index 0000000..d318c25 --- /dev/null +++ b/LeetCode/problem014_LongestCommonPrefix_test.go @@ -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) + } + }) + } +}