Start learning free

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

Word Lengths in C++: Mapping Words to Their Sizes

Practice Read the full explanation

Given a vector of strings words, return a vector of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in C++, explained

    Problem overview

    The function wordLengths takes a vector<string> named words and returns a vector<int> with the number of letters of each word, in the same order. For ["I", "love", "pancakes"] the answer is [1, 4, 8]. For ["banana", "kiwi", "fig"] it is [6, 4, 3], and for the single word ["code"] it is [4].

    Approach: one result per input

    This is the transform pattern: every input element produces exactly one output element. You create an empty result, visit each word once, and append that word's length. The result is as long as words, and because you append in the order you visit, the lengths line up with the words.

    Compare this with the filter pattern, where only some elements make it into the result. Here nothing is skipped: there is no if, and the loop body is a single statement. If you can say "one answer per element", this is the shape to reach for.

    Step by step

    1. Create lengths. It is a vector<int>, and it starts empty because no length has been computed yet.
    2. Loop over words. A range-based for gives the loop one string named word per turn.
    3. Append the length. word.size() is the number of characters, and push_back puts it at the end of lengths.
    4. Return after the loop. Returning inside the loop would send back a vector with only the first length.

    The solution in C++

    class Solution {
    public:
        vector<int> wordLengths(vector<string> &words) {
            vector<int> lengths;
            for (string word : words) {
                lengths.push_back(word.size());
            }
            return lengths;
        }
    };
    

    The C++ details worth knowing:

    • size() returns an unsigned number. Its type is size_t, and push_back into a vector<int> converts it to int silently. Word lengths are far below the int limit, so nothing is lost.
    • size() counts bytes. For the English letters in this lesson, one letter is one byte, so the count is the number of letters. Text with accented or other non-ASCII characters can use several bytes per character in a string.
    • for (string word : words) copies each word. The loop only needs size(), so for (const string &word : words) would give the same result without the copies.
    • The vector grows as needed. push_back takes care of the memory; you never declare a size.

    Reading the result

    The returned vector can be used like any other. Its size() equals the number of words, and lengths[0] is the length of the first word. For ["I", "love", "pancakes"], lengths[2] is 8. Because the order is kept, position i of the result always describes position i of words, which is what lets you pair them up later. If a word list is empty, the loop never runs and an empty vector comes back, although this lesson always gives at least one word.

    Edge cases and common mistakes

    • Returning too early. Put return lengths; after the closing brace of the loop.
    • Using lengths[i] = ... on an empty vector. Indexing a vector doesn't add elements, so writing past its end is undefined behaviour. Use push_back to add.
    • Uppercase letters. They count like lowercase ones: the length of "Hello" is 5.
    • One word. ["code"] gives a vector with a single element, [4].

    Testing

    • ["I", "love", "pancakes"] gives [1, 4, 8].
    • ["banana", "kiwi", "fig"] gives [6, 4, 3].
    • ["code"] gives [4].
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free