Start learning free

LESSON 225 OF 292 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Longest Word in Swift: 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

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in Swift, explained

    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

    1. Store words[0] in a var named longest. It is a variable because a longer word will replace it.
    2. Loop over every word with for word in words.
    3. Compare lengths with word.count > longest.count, using > and not >=.
    4. Replace the candidate with word when it is longer.
    5. Return longest after 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.first returns an optional that is nil when there is nothing.
    • Strings compare by character count here. word.count and longest.count are plain Int values, so > is a numeric comparison.
    • Value semantics. longest = word copies 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".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free