Problem overview
The function longestWord receives an array of strings, words, and returns the one with the most letters. When several words share the greatest length, the first of them is the answer. The array always has at least one word.
For ["apple", "kiwi", "mango"] the answer is "apple". "apple" and "mango" both have 5 letters, and "apple" comes first.
Approach: keep a champion
This is the "best so far" pattern. Hold one candidate, compare every word against it, and replace it whenever a word beats it. When the loop ends, the candidate has beaten, or tied and kept its place against, every word.
The candidate has to start as something real, and the first word is the natural choice: the array is never empty, so words[0] exists, and before any comparison it is the best word we have seen.
Ties are settled by the comparison. A word replaces the candidate only if it is strictly longer. A word of equal length doesn't replace it, so the earliest of the longest words stays.
Step by step
- Store
words[0]in avarnamedlongest. It is a variable because a longer word will replace it. - Loop over every word with
for word in words. - Compare lengths with
word.count > longest.count, using>and not>=. - Replace the candidate with
wordwhen it is longer. - Return
longestafter the loop.
The solution in Swift
class Solution {
func longestWord(_ words: [String]) -> String {
var longest = words[0]
for word in words {
if word.count > longest.count {
longest = word
}
}
return longest
}
}
The loop starts again at words[0], so the first word is compared with itself. That is harmless: its length isn't greater than its own length, so nothing changes.
Tracing ["I", "love", "pancakes"]: longest starts as "I" (1). "I" doesn't beat itself. "love" (4) beats 1, so it becomes the candidate. "pancakes" (8) beats 4, so the final answer is "pancakes".
The same pattern finds the shortest word (flip the comparison to <), the largest number in an array, or the highest score. Only the starting value and the test change.
Swift details
words[0]traps on an empty array. Indexing out of bounds crashes the program at run time. The constraint promises at least one word, so it is safe here. For an array that might be empty,words.firstreturns an optional that isnilwhen there is nothing.- Strings compare by character count here.
word.countandlongest.countare plainIntvalues, so>is a numeric comparison. - Value semantics.
longest = wordcopies the string. Strings are value types in Swift, so there is no shared object to worry about.
Edge cases and common mistakes
- Using
>=. On["apple", "kiwi", "mango"]it would return "mango", the last of the longest words, instead of "apple". - One word.
["code"]returns "code". - Starting with an empty string. It works if every word is compared, but starting from
words[0]avoids inventing a value of your own. - Returning the length. The function returns the word, not
longest.count.
Testing
["I", "love", "pancakes"]gives "pancakes".["apple", "kiwi", "mango"]gives "apple".["code"]gives "code".
