Start learning free

LESSON 223 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Lengths in Go: Mapping a Slice with append

Practice Read the full explanation

Given a slice of strings words, return a slice 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

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in Go, explained

    Problem overview

    The function wordLengths receives a slice of strings, words, and returns a slice of integers: the length of each word, in the same order. For ["I", "love", "pancakes"] the result is [1 4 8].

    The input has at least one word, and the words are made of English letters, so a word's length is its number of letters.

    Approach: one output per input

    This is the "map" pattern: every element of the input produces exactly one element of the output. The new slice starts empty, the loop visits the words in order, and each length is added at the end. Since the order of visiting and the order of adding are the same, the lengths line up with the words.

    Step by step

    1. Start with an empty []int. The result holds integers, not strings, so its type differs from the input's. It is declared with := and grows as values are appended.
    2. Loop with range. for _, word := range words gives each element as word. The first value that range produces is the index, and _ discards it.
    3. Append the length. len(word) is an int, which matches the slice's element type. append returns the longer slice, which goes back into lengths.
    4. Return after the loop. A return inside the loop would send back after the first word.

    Tracing the example

    With ["I", "love", "pancakes"], lengths grows by one value per word. After "I" it is [1], after "love" it is [1 4], and after "pancakes" it is [1 4 8]. The loop never skips a word and never adds two values for one word, so the result has as many entries as the input.

    Where the lengths go matters as much as what they are: each new value lands at the end, behind the earlier ones, so the position of a length in the result is the position of its word in the input.

    The solution in Go

    func wordLengths(words []string) []int {
        lengths := []int{}
        for _, word := range words {
            lengths = append(lengths, len(word))
        }
        return lengths
    }
    

    Go details worth knowing

    • The loop variable word is a copy of the element. Changing it would not change words; here it is only read.
    • len counts bytes in a string. That equals the number of letters for plain English letters. For text with accented letters, such as "héllo", len gives 6 while len([]rune("héllo")) gives 5.
    • You could allocate the result up front with make([]int, len(words)) and assign lengths[i] by index. The append version needs no index bookkeeping, and for a slice this size it is just as clear.

    Edge cases and common mistakes

    • A single word. ["code"] gives [4].
    • Uppercase letters count the same as lowercase ones: the length depends on how many letters there are, not on their case.
    • Discarding append's result (writing append(lengths, len(word)) alone) leaves lengths empty, and Go refuses to compile that line anyway.
    • Using the index instead of the word. If you keep the index and drop the word, you would add 0, 1, 2 rather than the lengths.

    Testing

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