Start learning free

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

Longest Word in Scala: Tracking the Best So Far

Practice Read the full explanation

Given an ArrayBuffer 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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in Scala, explained

    Problem overview

    The method longestWord receives an ArrayBuffer[String] named words and returns the word with the most letters. If several words share the greatest length, the first of them wins. There is always at least one word.

    For ArrayBuffer("I", "love", "pancakes") the answer is pancakes (8 letters). For ArrayBuffer("apple", "kiwi", "mango") both "apple" and "mango" have 5 letters, so the answer is apple.

    Approach

    Keep the longest word seen so far and let every word try to beat it. Start with the first word, which is the best candidate before anything else is looked at. When a word is strictly longer than the current best, it replaces it. A word of equal length does not replace it, and that is what makes the first of a tie win.

    Step by step

    1. Start with the first word. var longest = words(0). It is a var because it will be reassigned. Indexing with parentheses is how Scala reads an element.
    2. Loop over the words with for (word <- words). The first word is compared with itself, which changes nothing.
    3. Compare lengths with word.length > longest.length, strictly greater.
    4. Replace the best inside the if.
    5. Return longest after the loop.

    The solution in Scala

    class Solution {
        def longestWord(words: ArrayBuffer[String]): String = {
            var longest = words(0)
            for (word <- words) {
                if (word.length > longest.length) {
                    longest = word
                }
            }
            return longest
        }
    }
    
    • var versus val. With val, the assignment longest = word would not compile. Use var for a value that changes.
    • Type inference. words(0) is a String, so longest is a String without an annotation.
    • Letters, not alphabetical order. Only length matters. Case does not: ArrayBuffer("ab", "Cd", "xyz", "XYZ") returns xyz, the first of the two 3-letter words.
    • Empty input. words(0) on an empty buffer throws an IndexOutOfBoundsException. The lesson guarantees at least one word.

    Why the first word is a safe start

    A "best so far" variable needs a first value, and the first element of the input is the natural choice because it is a real candidate. Starting from a made-up value, such as an empty string, only works if the data can't contradict it. The lesson guarantees at least one word, so words(0) always exists.

    The loop then keeps one invariant: at any moment, longest is the first longest word among the words visited so far. A new word breaks a tie only if it is strictly longer, so an equal-length word, which comes later in the buffer, never takes the place of an earlier one. When the loop ends, the words visited are all of them, and the invariant gives the answer.

    Following the loop

    Take ArrayBuffer("apple", "kiwi", "mango", "banana"). The variable starts as apple:

    wordlengthlongest afterwards
    apple5apple
    kiwi4apple
    mango5apple
    banana6banana

    "mango" ties with "apple" at 5 letters and doesn't replace it, because 5 > 5 is false. Only "banana", with 6, takes over. The library has a shortcut too: words.maxBy(_.length) returns apple for ArrayBuffer("apple", "kiwi", "mango"), the same answer as the loop.

    Edge cases and common mistakes

    • Using >=. The last word of a tie would win, and ArrayBuffer("apple", "kiwi", "mango") would return mango.
    • Starting with an empty string. It works for non-empty words, but starting with words(0) needs no assumption about the contents.
    • One word. ArrayBuffer("code") returns code.

    Testing

    • ArrayBuffer("I", "love", "pancakes") gives pancakes.
    • ArrayBuffer("apple", "kiwi", "mango") gives apple.
    • ArrayBuffer("code") gives code.
    • ArrayBuffer("ab", "Cd", "xyz", "XYZ") gives xyz.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free