Problem overview
The method longestWord receives a list of strings, words, and returns the word with the most letters. When several words share the greatest length, it returns the first of them. The list always has at least one word.
For ["I", "love", "pancakes"] the answer is pancakes, which has 8 letters. For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5, so the answer is apple, the one that comes first. With a single word, ["code"], that word is the answer.
Approach: keep a champion
Read the words one at a time and remember the longest one seen so far. Each new word either beats the champion, in which case it takes over, or it doesn't, and the champion stays. After the last word, the champion is the longest of all.
The champion needs a starting value. Because the list is never empty, the first word is a safe choice: before any comparison, it is the best word we have.
Step by step
- Store
words[0]inlongest. This works because there is always at least one word. - Loop over
wordswithfor word in words. Each word gets one chance to beat the champion. - Compare lengths with
len(word) > len(longest). The comparison is strict. A word of equal length does not replace the champion, so on a tie the earlier word stays. - Replace the champion inside the
ifwithlongest = word. - Return
longestafter the loop, when every word has been compared.
Tracing the tie example
Take ["apple", "kiwi", "mango"]. The champion starts as "apple". The loop then asks, for each word, whether it is strictly longer than the champion:
word | longer than the champion "apple"? |
|---|---|
| apple | False |
| kiwi | False |
| mango | False |
"mango" matches "apple" at 5 letters but doesn't exceed it, so the champion never changes and the function returns apple.
The solution in Python
class Solution:
def longestWord(self, words: List[str]) -> str:
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
return longest
Notes on the code:
- The first word is compared with itself. The loop starts at the first word, and
len(words[0]) > len(longest)is false because they are the same string. It is harmless, and it keeps the loop simple. - Assigning a string only rebinds the name. Strings are immutable, and
longest = wordmakeslongestrefer to the same string asword. Nothing is copied or changed. - The built-in alternative.
max(words, key=len)does the same job, and it also returns the first longest word on a tie. Writing the loop once shows whatmaxdoes for you.
Edge cases and common mistakes
- Using
>=. With["apple", "kiwi", "mango"]the loop would end withmango, because the last word of the longest length would win every tie. The task asks for the first. - Starting with an empty string.
longest = ""also works for words that have letters. Starting fromwords[0]is the more general habit, since it also works for values such as numbers, where there is no obvious "empty" starting point. - Returning its length. The function returns the word itself, not
len(longest). - Comparing the strings directly.
word > longestcompares alphabetical order, not length. "pancakes" and "zoo" show the difference: "zoo" is the greater string, but "pancakes" is the longer one.
Testing
["I", "love", "pancakes"]givespancakes.["apple", "kiwi", "mango"]givesapple.["code"]givescode.
