Start learning free

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

Long Words Only in Rust: Filtering a Vec with a Loop

Practice Read the full explanation

Given an array of strings words and an integer n, return the words that are longer than n characters.

A word must be strictly longer than n: a word with exactly n characters is left out. Keep the words in the order they have in words. If no word is long enough, the result is empty.

 

Example 1:

Input: words = ["apple", "kiwi", "banana", "fig"], n = 4
Output: ["apple", "banana"]
Explanation: apple has 5 characters and banana has 6. kiwi has exactly 4, so it is left out, and fig has only 3.

Example 2:

Input: words = ["hi", "to", "be"], n = 3
Output: []
Explanation: No word has more than 3 characters.

Example 3:

Input: words = ["go", "went", "gone", "went"], n = 3
Output: ["went", "gone", "went"]
Explanation: Every word longer than 3 characters is kept, a repeated one too, in its original order.

 

Constraints:

  • words has at least one word, and every word is made of lowercase English letters.
  • n is 0 or more.
STEP 1 OF 5
    Ctrl + Enter to check

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in Rust, explained

    Problem overview

    The function long_words receives a vector of strings, words, and a number n. It returns a new vector holding only the words that are strictly longer than n characters, in their original order. A word with exactly n characters is left out, and if nothing qualifies the result is an empty vector.

    With words = ["apple", "kiwi", "banana", "fig"] and n = 4, the result is ["apple", "banana"]. "kiwi" has exactly 4 letters, which is not more than 4, and "fig" has 3. With ["go", "went", "gone", "went"] and n = 3, the result is ["went", "gone", "went"]: a repeated word is kept every time it appears.

    Approach: build a result as you scan

    This is the filter pattern. Start with an empty collection, look at each item once, and add the item to the collection when it passes a test. Because the loop visits the words from first to last and each one is added at the end, the order is preserved without any extra work.

    Step by step

    1. Create the empty result. It is a Vec<String> declared with let mut, since words will be pushed into it.
    2. Loop over the words. The loop goes over words itself, not over a reference to it, so each String is moved out of the vector into the variable word.
    3. Test the length. word.len() > n uses a strict comparison. Writing >= would wrongly keep the words of exactly n characters.
    4. Push the word. result.push(word) adds it at the end of the vector.
    5. Return the result. It is the last expression of the function, so it has no semicolon.

    The solution in Rust

    impl Solution {
        fn long_words(words: Vec<String>, n: usize) -> Vec<String> {
            let mut result: Vec<String> = Vec::new();
            for word in words {
                if word.len() > n {
                    result.push(word);
                }
            }
            result
        }
    }
    

    The Rust details worth a closer look:

    • Moving the words. for word in words consumes the vector. Each String is handed to the loop body, and result.push(word) moves it again into the result, so no text is copied. After the loop, words can't be used any more. Words that fail the test are simply dropped at the end of their iteration.
    • n is a usize. len() returns a usize, and Rust only compares two numbers of the same type, so n has that type too. It can't be negative, which matches the lesson's rule that n is 0 or more.
    • len() counts bytes. For the lowercase English letters of this lesson, one byte is one letter. For text with accents, "café".len() is 5 although it has four characters; chars().count() gives 4.
    • The last expression. result without a semicolon is the function's return value. Adding a semicolon would turn it into a statement, and the function would no longer return a vector.

    Edge cases and common mistakes

    • Using >=. With ["apple", "kiwi", "banana", "fig"] and n = 4 it would also return "kiwi".
    • No match. ["hi", "to", "be"] with n = 3 returns [], because the empty result is never pushed to.
    • n = 0. Every non-empty word is longer than 0, so all words are returned.
    • Duplicates. Nothing removes repeated words; each occurrence passes or fails on its own length.

    Testing

    • ["apple", "kiwi", "banana", "fig"], n = 4 gives ["apple", "banana"].
    • ["hi", "to", "be"], n = 3 gives [].
    • ["go", "went", "gone", "went"], n = 3 gives ["went", "gone", "went"].
    • ["go", "to"], n = 0 gives ["go", "to"].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free