Longest Common Prefix Scan (Go)
Walk the first word column by column and compare against every other word, returning the longest common prefix as soon as any column diverges or ends.
Code
package main
import "fmt"
// longest common prefix via a vertical scan, one column at a time
func longestCommonPrefix(words []string) string {
if len(words) == 0 {
return ""
}
for i, r := range words[0] {
for _, w := range words[1:] {
if i >= len(w) || rune(w[i]) != r {
return words[0][:i]
}
}
}
return words[0]
}
func main() {
for _, group := range [][]string{
{"flower", "flow", "flight"},
{"dog", "racecar", "car"},
{"interspecies", "interstellar", "interstate"},
} {
fmt.Printf("prefix: %q\n", longestCommonPrefix(group))
}
}Longest Common Prefix Scan (Go): the mechanics
All of the logic lives in the functions longestCommonPrefix and main.
Repetition is confined to for i, r := range words[0] — the rest of the file is straight-line.
Caveats
- Install step: none. The standard library covers every call.
Applying it
The entry definition is func longestCommonPrefix(words []string) string
prefix: labels the output line by line.
Execute the file and main walks through longestCommonPrefix, in that order.
Statements that matter
for _, group := range [][]string{
{"flower", "flow", "flight"},
{"dog", "racecar", "car"},
{"interspecies", "interstellar", "interstate"},
} {
fmt.Printf("prefix: %q\n", longestCommonPrefix(group))
}
for _, w := range words[1:] {
if i >= len(w) || rune(w[i]) != r {
return words[0][:i]
}
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Longest Common Prefix Scan (Go) print when run?
- The script runs standalone; its 1 labeled outputs include `prefix:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.