[Go] LeetCode 14. Longest Common Prefix

TAKASHI NARIKAWA
Jan 18 · 1 min read

Description

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

Solution

/*Go Approach 1: Horizontal scanning*/
/*Time complexity : O(S), where S is the sum of all characters in all strings.*/
/*Space complexity : O(1). We only used constant extra space. */
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
// Assume prefix
prefix := strs[0]
for i := 1; i < len(strs); i++ {
for !strings.HasPrefix(strs[i], prefix) {
prefix = prefix[0:len(prefix)-1]
if len(prefix) == 0 {
return ""
}
}
}
return prefix
}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade