Problem overview
The method longestWord receives an array of strings, words, and returns the one with the most letters. When several words share the longest length, it returns the first of them. The array always has at least one word.
For ["I", "love", "pancakes"] the answer is "pancakes", with 8 letters. For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5 letters, so the answer is "apple", which comes first.
Approach
Keep a variable with the longest word seen so far and compare every word against it. A longer word replaces it. At the end, the variable holds the longest word of the whole array.
The variable needs a starting value. Since the array has at least one word, the first word is a safe choice: before looking at anything else, it is the best candidate there is.
Ties are settled by the comparison. Only a strictly longer word replaces the current one, so a word of equal length never takes its place, and the first of the longest words stays.
Step by step
- Start with the first word. Store
words[0]inlongest, declared withletbecause it will be reassigned. - Loop over the words with
for (const word of words). Each word gets one chance to beatlongest. - Compare lengths. The
ifchecksword.length > longest.length, with>and not>=. - Replace. Inside the
if, assignwordtolongest. - Return after the loop. Every word has been compared by then.
The solution in TypeScript
class Solution {
longestWord(words: string[]): string {
let longest: string = words[0];
for (const word of words) {
if (word.length > longest.length) {
longest = word;
}
}
return longest;
}
}
Details worth knowing:
- The first word is compared with itself. The loop starts at index 0 too. The comparison is false (equal lengths), so nothing changes. It is harmless, and it keeps the loop simple.
- Index access can give
undefined.words[0]on an empty array isundefinedat run time, and the type annotation does not prevent that. The lesson promises at least one word, so this method doesn't handle the empty case. - Strings are compared by
lengthhere, not alphabetically.>on the numbersword.lengthandlongest.lengthcompares sizes. Comparing the strings themselves with>would compare them in dictionary order.
Edge cases and common mistakes
- Using
>=. The last word of the longest length would win. For["apple", "kiwi", "mango"]it would return "mango". - One word.
["code"]returns"code": nothing is longer than the starting value. - Starting with an empty string. It works for non-empty words, but the first word is simpler and also matches the lesson's guarantee.
- Returning the length. The method returns the word, not
longest.length. - Sorting the array. It does more work than a single pass, and the tie rule then depends on how the sort treats equal lengths. The single pass handles it with one comparison.
Testing
["I", "love", "pancakes"]gives"pancakes".["apple", "kiwi", "mango"]gives"apple".["code"]gives"code".["kiwi", "fig", "pear"]gives"kiwi": "kiwi" and "pear" tie, and "kiwi" is first.
