[Go] LeetCode 14. Longest Common Prefix

TAKASHI NARIKAWA
1 min readJan 18, 2020

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
}

--

--

TAKASHI NARIKAWA

Site Reliablity Engineer in Tokyo. SRE/devops/Go/AWS/Terraform/Kubernetes/Docker