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.

GoData Integrity

Code

gosnippet
28 lines
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

FAQ

What does Longest Common Prefix Scan (Go) print when run?
The script runs standalone; its 1 labeled outputs include `prefix:`.