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
- Start with the first word.
var longest = words[0]. It has to be avar, because a longer word will replace it. - Loop over every word.
for (word in words)also visits the first word again. Comparing it with itself does nothing, so that is harmless. - Compare lengths with
>.word.length > longest.lengthis true only for a strictly longer word. Using>=would let the last of the tied words win. - Replace the champion with
longest = wordinside theif. - Return
longestafter 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 aString, solongestis aStringand later assignments must be strings too. No type annotation is needed. - Indexing a list.
words[0]callsget(0). On an empty list it throws anIndexOutOfBoundsException, which is why the lesson guarantees at least one word. - A
varholds a reference.longest = worddoesn'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"]returnsabc, notxyz. With>=it would returnxyz. - 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"]givespancakes.["apple", "kiwi", "mango"]givesapple.["code"]givescode.["ab", "cd", "abc", "xyz"]givesabc.
