package main import ( "fmt" ) func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } prefix := strs[0] for _, s := range strs[1:] { for len(prefix) > 0 && (len(s) < len(prefix) || s[:len(prefix)] != prefix) { prefix = prefix[:len(prefix)-1] } } return prefix } func main() { words := []string{"flower", "flow", "flight"} fmt.Println(longestCommonPrefix(words)) }
The function starts with the first string as the prefix. It then compares this prefix with each string in the list. If the current prefix is not a prefix of the string, it shortens the prefix by one character from the end until it matches or becomes empty. For the input ["flower", "flow", "flight"], the longest common prefix is "fl".
package main import "fmt" func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } prefix := strs[0] for _, s := range strs[1:] { for len(prefix) > 0 && (len(s) < len(prefix) || s[:len(prefix)] != prefix) { prefix = prefix[:len(prefix)-1] } } return prefix } func main() { words := []string{"", "b", "c"} fmt.Println(longestCommonPrefix(words)) }
Since one of the strings is empty, the longest common prefix must be empty. The function returns an empty string "".
package main import "fmt" func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } prefix := strs[0] for _, s := range strs[1:] { for len(prefix) > 0 && (len(s) < len(prefix) || s[:len(prefix)] != prefix) { prefix = prefix[:len(prefix)-1] } } return prefix } func main() { words := []string{"dog", "racecar", "car"} fmt.Println(longestCommonPrefix(words)) }
The code does not check if the current string is shorter than the prefix before slicing. When s is shorter than prefix, s[:len(prefix)] causes a runtime error due to out-of-range slicing.
The algorithm compares characters one by one across all strings until a mismatch is found. In the worst case, it compares all characters of all strings, so the complexity is O(S), where S is the total number of characters.
All strings start with "int". After "int", the strings diverge: "erview", "errupt", "egrate", "egral". So the longest common prefix is "int".
