[Go] LeetCode 14. Longest Common Prefix

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
}

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
TAKASHI NARIKAWA

TAKASHI NARIKAWA

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

More from Medium

Leetcode — Reconstruct Itinerary

Why does Competitive Programming love Data Structures and Algorithms?

Linked List | LeetCode Top Interview Questions

A Visual Intro to Complete Binary Tree, Heaps, and Heap Sort (with source code - Python)