Start learning free

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

Long Words Only in Scala: Filtering with ArrayBuffer

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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in Scala, explained

    Problem overview

    The method longWords receives an Array[String] called words and an Int called n. It returns the words that have more than n characters, as a List[String], in the order they have in words.

    With words = Array("apple", "kiwi", "banana", "fig") and n = 4, the result is List(apple, banana). "kiwi" has exactly 4 characters, and the condition is strictly "longer than", so it is left out. With Array("hi", "to", "be") and n = 3, no word is long enough and the result is an empty List().

    Approach

    Look at each word once and keep it if it passes the test. Because the words are visited from first to last and each kept word goes at the end of the collection, the original order is preserved with no extra work. Repeated words are kept as many times as they appear: Array("go", "went", "gone", "went") with n = 3 gives List(went, gone, went).

    Step by step

    1. Create an empty buffer. A val named result holds a scala.collection.mutable.ArrayBuffer[String]. The full package path is written out, so no import is needed.
    2. Loop over the words with for (word <- words).
    3. Test the length. word.length > n is true only for words with more than n characters.
    4. Append the word with +=.
    5. Return the buffer as a list. The method's return type is List[String], so result.toList converts the buffer.

    The solution in Scala

    class Solution {
        def longWords(words: Array[String], n: Int): List[String] = {
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (word <- words) {
                if (word.length > n) {
                    result += word
                }
            }
            return result.toList
        }
    }
    

    A few Scala details:

    • val with a changeable buffer. val means result always refers to the same buffer; it does not make the buffer read-only. An ArrayBuffer can grow, which is why += works on it.
    • Why a buffer and not a List. A List is immutable, so it has no += that changes it in place. Collecting into a buffer and converting once at the end is the simplest fit for a loop.
    • toList copies. The returned List is a separate, immutable collection; later changes to the buffer would not show up in it.
    • return. The last expression of a block is its value in Scala, so result.toList alone would do. The explicit return is correct too.
    • Arrays versus lists. words is an Array, which is mutable and has a fixed size. The loop only reads it.

    Mutable and immutable collections

    Scala's everyday collections, List, Vector and Map, are immutable by default: once built, they never change, and operations like :+ return a new collection. The changeable versions live in the package scala.collection.mutable. This lesson uses a mutable ArrayBuffer as scratch space while the loop runs, and hands back an immutable List at the end, so the caller gets a value nobody can modify behind its back.

    The condition is the whole lesson. It compares word.length with n using >, so the boundary case, a word with exactly n characters, is decided by one character of code.

    Following the loop

    With words = Array("apple", "kiwi", "banana", "fig") and n = 4, the buffer changes like this as each word is checked:

    wordlengthbuffer afterwards
    apple5ArrayBuffer(apple)
    kiwi4ArrayBuffer(apple)
    banana6ArrayBuffer(apple, banana)
    fig3ArrayBuffer(apple, banana)

    Scala's collections can also do this in one expression: words.filter(_.length > 4).toList gives the same List(apple, banana). The loop version makes each step visible, and filter is what you reach for once the loop feels familiar.

    Edge cases and common mistakes

    • Using >=. That keeps words of exactly n characters. For "kiwi" and n = 4 it would wrongly return List(apple, kiwi, banana).
    • No match. The buffer stays empty and the method returns List(), which is the correct answer.
    • n = 0. Every word has at least one letter, so Array("cat", "dog") comes back whole.
    • Deduplicating. Repeated words must stay; don't use a set.

    Testing

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