Problem overview
The function longestWord takes a slice of strings, words, and returns the word with the most letters. When several words share the greatest length, the first of them is the answer. The slice always has at least one word.
For ["apple", "kiwi", "mango"] the answer is apple: it and "mango" both have 5 letters, and "apple" comes first.
Approach: keep a champion
You don't need to sort or to measure every word first. Keep a variable, longest, holding the longest word seen so far, and let each word challenge it. If a word is longer, it becomes the new champion. When the loop ends, every word has been compared, so the champion is the longest overall.
The champion has to start as something real. The first word is a good choice: before looking at anything else, it is the best you have. That is also why the problem promises at least one word, since words[0] must exist.
Step by step
- Store
words[0]inlongest. It is declared with:=, so its type isstring. - Loop over the words with
for _, word := range words. - Compare lengths.
len(word) > len(longest)asks whether the challenger is longer than the champion. - Replace the champion by assigning
longest = word. - Return
longestafter the loop.
The comparison is strict. With >=, an equally long word would replace the champion, and on a tie the last longest word would win instead of the first.
Tracing a tie
Take ["apple", "kiwi", "mango"]. The champion starts as "apple" (5 letters). "apple" itself is not longer than the champion, so nothing changes. "kiwi" has 4 letters, so nothing changes. "mango" has 5 letters, equal to the champion's 5, so the strict > is false and "apple" stays. The function returns apple.
The same loop on ["I", "love", "pancakes"] replaces the champion twice: "love" (4) beats "I" (1), then "pancakes" (8) beats "love".
The solution in Go
func longestWord(words []string) string {
longest := words[0]
for _, word := range words {
if len(word) > len(longest) {
longest = word
}
}
return longest
}
Go details worth knowing
- The loop compares the first word with itself at the start. That is harmless, because
len(word) > len(longest)is false for equal lengths, and it keeps the loop simple. Starting at index 1 would also work. words[0]on an empty slice panics with an index-out-of-range error. The lesson guarantees at least one word; in your own code you would checklen(words)first.- Strings are immutable values, so
longest = wordjust points the variable at another string. Nothing is copied character by character. lencounts bytes. For English letters that equals the number of letters.
Edge cases and common mistakes
- A tie.
["apple", "kiwi", "mango"]returnsapple, becausemangois not strictly longer. - One word.
["code"]returnscode. - Tracking the length instead of the word. A variable holding only the maximum length can't give back the word. Keep the word and call
lenon it when comparing. - Starting
longestas an empty string. That works for non-empty words too, but starting fromwords[0]avoids a made-up starting value.
Testing
["I", "love", "pancakes"]returnspancakes.["apple", "kiwi", "mango"]returnsapple.["code"]returnscode.
