Problem overview
The method longestWord receives a List<String> and returns the word with the most letters. If several words share the longest length, it returns the first of them. For ["I", "love", "pancakes"] the answer is pancakes. For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5 letters, and "apple" comes first, so it wins. A list with one word returns that word.
Approach: keep a champion
You don't need to sort the words or compute every length first. Start with the first word as the champion. Then look at each word and, whenever it is longer than the champion, replace the champion. After the last word, the champion is the longest one. The same pattern finds a maximum number, a smallest value or a best score.
The ties are decided by one character in the comparison. Replacing the champion only when a word is strictly longer means that an equally long later word never takes over, so the first of the longest words stays.
Step by step
- Start with the first word.
String longest = words.get(0);is safe because the lesson guarantees at least one word. Before any comparison, it is the best word seen so far. - Loop over the words with
for (String word : words). Every word gets one chance to beat the champion. The first pass compares the first word with itself, which changes nothing. - Compare lengths with
>.word.length() > longest.length()is true only for a strictly longer word. - Replace the champion inside the
if:longest = word;. - Return
longestafter the loop, when every word has been compared.
The solution in Java
class Solution {
public String longestWord(List<String> words) {
String longest = words.get(0);
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
return longest;
}
}
Details worth knowing:
List.get(0). Lists are read withget(index), not with square brackets. On an empty list,get(0)throws anIndexOutOfBoundsException, which is why the guarantee of at least one word matters.- The variable holds a reference.
longest = worddoesn't copy the characters; both names point to the same string, and strings can't be changed, so that is harmless. - Ties. With
["ab", "cd", "ef", "abc", "xyz"]the method returnsabc: "xyz" has the same length, but it isn't strictly longer.
Watching the champion change
For ["apple", "kiwi", "mango", "fig", "banana"], this is the value of longest after each word has been looked at:
apple -> apple
kiwi -> apple
mango -> apple
fig -> apple
banana -> banana
"mango" ties "apple" at 5 letters and doesn't replace it. Only "banana", with 6, takes over. The champion changes at most once per word, and it never goes back to a shorter word, which is why one pass is enough.
An empty list is outside the lesson's rules. Calling get(0) on one fails with Index 0 out of bounds for length 0. If you ever need to handle that case, check words.isEmpty() before the loop and decide what to return.
Edge cases and common mistakes
- Using
>=. The last of the longest words would win instead of the first. For["apple", "kiwi", "mango"]the answer would bemango. - Starting with an empty string. It works for non-empty words, but starting with
words.get(0)is the habit that also works for numbers, where no neutral starting value exists. - Comparing the strings themselves.
word > longestdoesn't compile in Java. Compare lengths, not the words. - Returning the length. The method returns the word, not its number of letters.
Testing
["I", "love", "pancakes"]givespancakes.["apple", "kiwi", "mango"]givesapple.["code"]givescode.["ab", "cd", "ef", "abc", "xyz"]givesabc.
