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
- Store
words[0]in astringnamedlongest. It is the longest word seen so far, because it is the only one seen. - Write a
foreachloop with astringnamedwordoverwords. - Compare lengths with
word.Length > longest.Length. Use>, not>=, so that a tie keeps the earlier word. - Replace
longestwithwordinside theif. - Return
longestafter 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 givemango. - 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.
