Start learning free

LESSON 218 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Long Words Only in C++: Filtering a Vector of Strings

Practice Read the full explanation

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

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in C++, explained

    Problem overview

    The function longWords receives a vector<string> named words and an int named n. It returns a new vector with the words that have more than n characters, in their original order. A word with exactly n characters is left out, and when no word qualifies, the result is an empty vector.

    With words = ["apple", "kiwi", "banana", "fig"] and n = 4, the function returns ["apple", "banana"]. "kiwi" has exactly 4 characters, so it fails the "strictly longer" test. With ["hi", "to", "be"] and n = 3 the result is [], and with ["go", "went", "gone", "went"] and n = 3 it is ["went", "gone", "went"]: a repeated word is kept every time it qualifies.

    Approach: filter into a new vector

    This is the filter pattern: walk through the input once, test each element, and copy the ones that pass into a result collection. The input stays untouched. Because the loop visits the words from first to last and each passing word is added at the end of the result, the order is preserved with no extra work.

    Step by step

    1. Create the result. A vector<string> declared without values starts empty. It will hold the words that pass.
    2. Loop over the words. A range-based for hands the loop one word per turn, in order.
    3. Test the length. word.size() > n is true only for words with more than n characters. Using >= would keep words of exactly n characters, which the task excludes.
    4. Add the word. push_back appends it to the end of result.
    5. Return after the loop. If nothing was added, result is still empty, which is the correct answer.

    The solution in C++

    class Solution {
    public:
        vector<string> longWords(vector<string> &words, int n) {
            vector<string> result;
            for (string word : words) {
                if (word.size() > n) {
                    result.push_back(word);
                }
            }
            return result;
        }
    };
    

    The C++ details worth knowing:

    • size() is unsigned. word.size() returns an unsigned type, while n is a signed int. When the two meet in a comparison, the signed value is converted to unsigned. That is harmless here because n is never negative, but with a negative number it would turn into a huge value: word.size() > -1 is false for every word, since -1 becomes the largest unsigned number. A compiler may warn about this comparison.
    • for (string word : words) copies. Each word is a copy of the element. That is fine for short words. For long strings, for (const string &word : words) reads the elements without copying them.
    • words is passed by reference. The & in the parameter avoids copying the whole vector when the function is called. The function doesn't change it.
    • Returning a vector is cheap. Returning result by value does not copy every string: the compiler moves it or builds it in place.

    Edge cases and common mistakes

    • >= instead of >. For the first example with n = 4, it would wrongly include "kiwi".
    • n = 0. Every word has at least one letter, so every word is kept.
    • Returning inside the loop. A return inside the if would send back after the first match instead of collecting them all.
    • Repeated words. They are not removed: each occurrence is tested and added on its own.

    Testing

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