Start learning free

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

Longest Word in Kotlin: Tracking the Best So Far

Practice Read the full explanation

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in Kotlin, explained

    Problem overview

    The function longestWord receives a list of strings and returns the one with the most letters. When several words share the longest length, it returns the first of them. For ["I", "love", "pancakes"] the answer is pancakes (8 letters, against 1 and 4). For ["apple", "kiwi", "mango"], apple and mango both have 5 letters, so the answer is apple, the one that comes first.

    Approach: a running champion

    Go through the words once and remember the longest one seen so far. Each new word challenges it: if the newcomer is longer, it takes over. The list is never empty, so the first word can start as the champion, and every word that follows gets one chance to beat it.

    The tie rule comes from the kind of comparison. A word of equal length must not replace the champion, so the challenge uses "strictly longer". The word that got there first stays.

    Step by step

    1. Start with the first word. var longest = words[0]. It has to be a var, because a longer word will replace it.
    2. Loop over every word. for (word in words) also visits the first word again. Comparing it with itself does nothing, so that is harmless.
    3. Compare lengths with >. word.length > longest.length is true only for a strictly longer word. Using >= would let the last of the tied words win.
    4. Replace the champion with longest = word inside the if.
    5. Return longest after the loop, once every word has had its turn.

    The solution in Kotlin

    class Solution {
        fun longestWord(words: List<String>): String {
            var longest = words[0]
            for (word in words) {
                if (word.length > longest.length) {
                    longest = word
                }
            }
            return longest
        }
    }
    

    Kotlin details worth knowing:

    • Type inference. words[0] is a String, so longest is a String and later assignments must be strings too. No type annotation is needed.
    • Indexing a list. words[0] calls get(0). On an empty list it throws an IndexOutOfBoundsException, which is why the lesson guarantees at least one word.
    • A var holds a reference. longest = word doesn't copy the text. It points the variable at the same string, which is safe because Kotlin strings can't change.

    Tracing the loop

    For ["apple", "kiwi", "mango"], here is longest after each word is examined:

    apple -> apple
    kiwi -> apple
    mango -> apple

    kiwi is shorter and never gets in. mango has the same length as apple, 5, and strict > keeps apple in front. Only a word with more than 5 letters could replace it.

    Kotlin's standard library can do this job in one call, words.maxByOrNull { it.length }, which also returns the first of the longest on a tie. The loop shows how that call decides.

    Edge cases and common mistakes

    • Ties. ["ab", "cd", "abc", "xyz"] returns abc, not xyz. With >= it would return xyz.
    • One word. The loop never finds a longer word, and the function returns the word it started with.
    • Returning the length. The function returns the word itself, a String, not its length.
    • Starting from an empty string. That also works for nonempty words, but starting from words[0] keeps the "first among equals" rule simple and needs no special value.

    Testing

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