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
- Start with the first word.
var longest = words(0). It is avarbecause it will be reassigned. Indexing with parentheses is how Scala reads an element. - Loop over the words with
for (word <- words). The first word is compared with itself, which changes nothing. - Compare lengths with
word.length > longest.length, strictly greater. - Replace the best inside the
if. - Return
longestafter 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
}
}
varversusval. Withval, the assignmentlongest = wordwould not compile. Usevarfor a value that changes.- Type inference.
words(0)is aString, solongestis aStringwithout an annotation. - Letters, not alphabetical order. Only
lengthmatters. Case does not:ArrayBuffer("ab", "Cd", "xyz", "XYZ")returnsxyz, the first of the two 3-letter words. - Empty input.
words(0)on an empty buffer throws anIndexOutOfBoundsException. 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:
| word | length | longest afterwards |
|---|---|---|
| apple | 5 | apple |
| kiwi | 4 | apple |
| mango | 5 | apple |
| banana | 6 | banana |
"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, andArrayBuffer("apple", "kiwi", "mango")would returnmango. - 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")returnscode.
Testing
ArrayBuffer("I", "love", "pancakes")givespancakes.ArrayBuffer("apple", "kiwi", "mango")givesapple.ArrayBuffer("code")givescode.ArrayBuffer("ab", "Cd", "xyz", "XYZ")givesxyz.
