Start learning free

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

Long Words Only in Go: Filtering a Slice

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

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in Go, explained

    Problem overview

    The function longWords takes a slice of strings, words, and an integer n. It returns a new slice with the words that have more than n characters, in the order they had in words. A word with exactly n characters is left out, and if nothing qualifies, the result is empty.

    With ["apple", "kiwi", "banana", "fig"] and n = 4, "apple" (5) and "banana" (6) pass. "kiwi" has exactly 4 characters, so it fails the test, and "fig" has 3. The result is [apple banana].

    Approach: build a new slice as you go

    This is the filter pattern: look at each element once, test it, and copy the ones that pass into a result. The input is never changed. Because the loop visits the words from first to last and each passing word goes at the end of the result, the original order is kept without any extra work.

    Step by step

    1. Create an empty result. []string{} is a slice with no elements, ready to grow.
    2. Loop over the words. for _, word := range words gives each element in turn. range produces an index and a value; the index is not needed, so it is assigned to the blank identifier _.
    3. Test the length. len(word) > n is true only when the word is strictly longer than n. Using >= would wrongly keep words of exactly n characters.
    4. Append the passing word. append returns the grown slice, so the result must be stored back in result.
    5. Return the result after the loop.

    Tracing the example

    With n = 4, the loop makes these decisions:

    wordlen(word)len(word) > 4result afterwards
    apple5true[apple]
    kiwi4false[apple]
    banana6true[apple banana]
    fig3false[apple banana]

    Only the rows with true change result, and they add to its end, so "apple" stays ahead of "banana".

    The solution in Go

    func longWords(words []string, n int) []string {
        result := []string{}
        for _, word := range words {
            if len(word) > n {
                result = append(result, word)
            }
        }
        return result
    }
    

    Go details worth knowing

    • append(result, word) on its own line does nothing useful. It may allocate a bigger array and returns a slice describing it, so the line must be result = append(result, word). Go also reports the unused result of append as a compile error.
    • len on a string counts bytes, not characters. For the lowercase English letters in this lesson the two are the same. A word like "héllo" has 5 characters but len gives 6, because é takes two bytes in UTF-8. Counting characters would need len([]rune(word)).
    • Starting with []string{} rather than var result []string means the function returns an empty, non-nil slice when nothing matches. Printing either one shows [], but the two differ when compared with nil.

    Edge cases and common mistakes

    • Nothing long enough. ["hi", "to", "be"] with n = 3 gives [], a slice of length 0.
    • Repeated words stay. ["go", "went", "gone", "went"] with n = 3 gives [went gone went]: the filter tests each word, not whether it has been seen before.
    • n = 0. Every word has at least one letter, so with n = 0 all of them pass. ["a", "bb"] returns [a bb].
    • Forgetting to store append's result leaves result empty.
    • Returning inside the loop would stop at the first long word instead of collecting them all.

    Testing

    Try these inputs in the editor above:

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