Start learning free

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

Word Lengths in Scala: Collecting Results in an ArrayBuffer

Practice Read the full explanation

Given an ArrayBuffer of strings words, return an ArrayBuffer 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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in Scala, explained

    Problem overview

    The method wordLengths receives an ArrayBuffer[String] named words and returns an ArrayBuffer[Int] with the length of each word, in the same order. For ArrayBuffer("I", "love", "pancakes") the result is ArrayBuffer(1, 4, 8).

    Approach

    One word gives exactly one length, so the loop runs once per word and adds one number to a new buffer each time. Adding at the end keeps the order: the first word's length is first, and so on. ArrayBuffer("banana", "kiwi", "fig") gives ArrayBuffer(6, 4, 3).

    Step by step

    1. Create the result. A val named lengths holds an empty ArrayBuffer[Int]().
    2. Loop over the words with for (word <- words).
    3. Append each length. word.length is the number of characters, and += adds it at the end of the buffer.
    4. Return after the loop. A return inside the loop would stop after the first word.

    The solution in Scala

    class Solution {
        def wordLengths(words: ArrayBuffer[String]): ArrayBuffer[Int] = {
            val lengths = ArrayBuffer[Int]()
            for (word <- words) {
                lengths += word.length
            }
            return lengths
        }
    }
    
    • val does not freeze the buffer. It only fixes which buffer lengths refers to. The buffer itself can still grow.
    • length without parentheses. On a String, word.length is written without (), and it counts characters.
    • ArrayBuffer[Int]() without new. The companion object's apply builds the buffer.
    • A shorter form. words.map(_.length) gives the same result for an ArrayBuffer. The lesson uses the explicit loop to practise building a result.

    What the for loop does

    for (word <- words) reads as "for each word in words". The part before <- is a new name that holds the current element on each pass, and the loop body runs once per element, from the first to the last. This form doesn't produce a value by itself: it runs its body for its side effects, here the += on the buffer.

    Scala has a second form, for (word <- words) yield word.length, which builds a new collection from the values of the body. For an ArrayBuffer it produces an ArrayBuffer(1, 4, 8) on the same input. The lesson uses the first form to practise creating a buffer, appending to it and returning it.

    The lesson's file already imports ArrayBuffer, so the short name works. In a program of your own, add import scala.collection.mutable.ArrayBuffer at the top.

    Where this pattern leads

    Turning each element of a collection into one new value is called mapping, and it is the most common shape of loop there is. The recipe never changes: create an empty result, visit every element, append the transformed value, return the result. Only the transformation, here word.length, differs from one problem to the next. Written with the library, the same idea is words.map(_.length), where _.length is a short way to write "take each word and ask for its length".

    Following the loop

    For ArrayBuffer("I", "love", "pancakes"), the buffer grows by one number per word:

    wordlengths afterwards
    IArrayBuffer(1)
    loveArrayBuffer(1, 4)
    pancakesArrayBuffer(1, 4, 8)

    The result always has as many entries as words, because the loop never skips a word and never adds two numbers for one word. Nothing here removes or reorders anything, so order is kept for free.

    Edge cases and common mistakes

    • One word. ArrayBuffer("code") gives ArrayBuffer(4).
    • Returning inside the loop. Only the first length would come back.
    • Using Array[Int] as the result type. The method's signature asks for an ArrayBuffer[Int], which can grow as the loop adds lengths; a plain Array has a fixed size.

    Testing

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