Start learning free

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

Longest Word in C#: Tracking the Best So Far

Practice Read the full explanation

Given a List 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

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in C#, explained

    Problem overview

    The method LongestWord receives a List<string> named words and returns the word with the most letters. When several words share the longest length, the first of them is the answer. The list 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, and apple comes first, so it wins. A list with just "code" returns code.

    Approach: keep the best word seen so far

    You don't need to sort the words or measure them all at once. Walk through the list and remember the longest word met so far. Each new word gets one chance to beat it: if the new word is longer, it takes the place of the old one. When the walk ends, the remembered word is the longest of all.

    The only question is where to start. Since the list is never empty, the first word is a safe starting guess: before looking at anything else, it is the best you have.

    Ties are settled by the comparison. If a new word has the same length as the current best, it must not replace it, so the test is "strictly longer". The first of the longest words then stays in place. With ["apple", "kiwi", "mango"], apple starts as the best, kiwi is shorter, and mango has the same length, so apple remains.

    Step by step

    1. Store words[0] in a string named longest. It is the longest word seen so far, because it is the only one seen.
    2. Write a foreach loop with a string named word over words.
    3. Compare lengths with word.Length > longest.Length. Use >, not >=, so that a tie keeps the earlier word.
    4. Replace longest with word inside the if.
    5. Return longest after the loop, once every word has been compared.

    The solution in C#

    class Solution {
        public string LongestWord(List<string> words) {
            string longest = words[0];
            foreach (string word in words) {
                if (word.Length > longest.Length) {
                    longest = word;
                }
            }
            return longest;
        }
    }

    The loop starts at the first word again, so it compares words[0] with itself. That is harmless: the lengths are equal, so nothing changes.

    The method uses words[0], which works on a List the same way as on an array. On an empty list it throws an ArgumentOutOfRangeException, which is why the lesson promises at least one word.

    Complexity

    The loop visits each of the n words once, and each comparison takes constant time, because a string already knows its length. The time is O(n). The method only stores one extra reference, so the extra space is O(1).

    Edge cases and common mistakes

    • Ties. With >= the last of the longest words would win, and ["apple", "kiwi", "mango"] would give mango.
    • Starting with an empty string. It also works as a start for non-empty words, but the first word is simpler and matches the single-word case directly.
    • Returning the length. The method returns the word, a string, not its length.
    • One word. The loop never replaces anything and the first word is returned.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free