Start learning free

LESSON 227 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Longest Word in Rust: Tracking a Maximum in a Loop

Practice Read the full explanation

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

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in Rust, explained

    Problem overview

    The function longest_word receives a vector of strings, words, and returns the word with the most letters. If several words share the longest length, the first of them is the answer. The vector 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.

    Approach: keep the best so far

    Scan the words once and remember the longest word seen up to now. Before the scan, the first word is the best candidate there is. Each later word either beats it or doesn't. When the scan ends, every word has had its chance, so the remembered word is the longest.

    The tie rule comes from the comparison. If a word replaces the best only when it is strictly longer, an equal-length word never takes over, and the earliest of the longest words stays.

    Step by step

    1. Start with the first word. words[0].clone() goes into a mutable variable, longest. The vector is never empty, so index 0 exists.
    2. Loop over &words. Each word is a borrowed reference to a string.
    3. Compare lengths with >. The test word.len() > longest.len() is strict, which keeps the first word on a tie.
    4. Replace the best with a copy of the word.
    5. Return longest after the loop.

    The solution in Rust

    impl Solution {
        fn longest_word(words: Vec<String>) -> String {
            let mut longest = words[0].clone();
            for word in &words {
                if word.len() > longest.len() {
                    longest = word.clone();
                }
            }
            return longest;
        }
    }
    

    The Rust details worth a closer look:

    • Why clone(). words[0] can't be moved out of the vector by indexing, because that would leave a hole in it. clone() makes an independent copy of the String, so longest owns its text. The same applies to longest = word.clone(), where word is only a reference.
    • Reassignment. Assigning to longest drops the string it held before. That is why the variable is declared with let mut.
    • Comparing lengths, not strings. len() returns a usize. Comparing the strings themselves with > would order them alphabetically, which is a different question.
    • The first word is compared with itself. The loop starts at the first word, which is already longest. That comparison is false and harmless.
    • Indexing panics on an empty vector. words[0] on an empty vector stops the program, which is why the lesson guarantees at least one word.

    Tracing a tie

    Take ["apple", "kiwi", "mango"]. longest starts as "apple" (5). "apple" is not longer than itself, so nothing changes. "kiwi" has 4 letters, which is not more than 5. "mango" has 5, which is not more than 5, so it doesn't replace "apple". The loop ends and "apple" is returned. A strict comparison is the entire tie rule; no extra code is needed.

    Another way to get the same answer is words.iter().max_by_key(|w| w.len()), but it returns the last maximum on a tie, so it would give "mango" here. Writing the loop by hand keeps control of the tie rule.

    Edge cases and common mistakes

    • Using >=. The last of the longest words would win. ["mango", "apple"] would then return "apple" instead of "mango".
    • Starting from an empty string. That works for non-empty words, but starting from the first word is clearer and also covers a single-word vector.
    • One word. ["code"] returns "code" without any replacement.
    • Returning the length. The function returns the word, a String, not its length.

    Testing

    • ["I", "love", "pancakes"] gives "pancakes".
    • ["apple", "kiwi", "mango"] gives "apple".
    • ["mango", "apple"] gives "mango".
    • ["code"] gives "code".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free