Start learning free

LESSON 224 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Longest Word in Go: Tracking the Best So Far

Practice Read the full explanation

Given a slice of strings words, return the longest word: the one with the most letters.

If several words share the longest length, return the first of them.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: "pancakes"
Explanation: "pancakes" has 8 letters, more than "I" (1) and "love" (4).

Example 2:

Input: words = ["apple", "kiwi", "mango"]
Output: "apple"
Explanation: "apple" and "mango" both have 5 letters, the most. "apple" comes first, so it is the answer.

Example 3:

Input: words = ["code"]
Output: "code"
Explanation: With only one word, it is the longest.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • On a tie, the answer is the first of the longest words.
STEP 1 OF 5
    Ctrl + Enter to check

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in Go, explained

    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

    1. Store words[0] in longest. It is declared with :=, so its type is string.
    2. Loop over the words with for _, word := range words.
    3. Compare lengths. len(word) > len(longest) asks whether the challenger is longer than the champion.
    4. Replace the champion by assigning longest = word.
    5. Return longest after 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 check len(words) first.
    • Strings are immutable values, so longest = word just points the variable at another string. Nothing is copied character by character.
    • len counts bytes. For English letters that equals the number of letters.

    Edge cases and common mistakes

    • A tie. ["apple", "kiwi", "mango"] returns apple, because mango is not strictly longer.
    • One word. ["code"] returns code.
    • 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 len on it when comparing.
    • Starting longest as an empty string. That works for non-empty words too, but starting from words[0] avoids a made-up starting value.

    Testing

    • ["I", "love", "pancakes"] returns pancakes.
    • ["apple", "kiwi", "mango"] returns apple.
    • ["code"] returns code.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free