Start learning free

LESSON 224 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Longest Word in TypeScript: Tracking the Best So Far

Practice Read the full explanation

Given an array of strings words, return the longest word: the one with the most letters.

If several words share the longest length, return the first of them.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: "pancakes"
Explanation: "pancakes" has 8 letters, more than "I" (1) and "love" (4).

Example 2:

Input: words = ["apple", "kiwi", "mango"]
Output: "apple"
Explanation: "apple" and "mango" both have 5 letters, the most. "apple" comes first, so it is the answer.

Example 3:

Input: words = ["code"]
Output: "code"
Explanation: With only one word, it is the longest.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • On a tie, the answer is the first of the longest words.
STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in TypeScript, explained

    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

    1. Start with the first word. Store words[0] in longest, declared with let because it will be reassigned.
    2. Loop over the words with for (const word of words). Each word gets one chance to beat longest.
    3. Compare lengths. The if checks word.length > longest.length, with > and not >=.
    4. Replace. Inside the if, assign word to longest.
    5. 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 is undefined at 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 length here, not alphabetically. > on the numbers word.length and longest.length compares 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.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free