Start learning free

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

Word Lengths in Kotlin: Building a List in a Loop

Practice Read the full explanation

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in Kotlin, explained

    Problem overview

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

    Approach: one number out for each word in

    The result has exactly as many items as words, and the item at each position depends only on the word at the same position. That makes it a loop with a list that grows: start empty, and for every word add its length at the end. Adding at the end keeps the order.

    Step by step

    1. Make an empty list of Int with mutableListOf<Int>() and store it in lengths. The val keyword means the name always refers to this list. It doesn't stop the list from growing.
    2. Loop over the words with for (word in words). The loop body runs once per word.
    3. Add the length. word.length is the number of characters in the string, and lengths.add(...) appends it.
    4. Return lengths after the loop. A return inside the loop would send back after the first word only.

    The solution in Kotlin

    class Solution {
        fun wordLengths(words: List<String>): List<Int> {
            val lengths = mutableListOf<Int>()
            for (word in words) {
                lengths.add(word.length)
            }
            return lengths
        }
    }
    

    Kotlin details worth knowing:

    • The type argument matters. mutableListOf<Int>() with nothing inside gives Kotlin no values to infer the element type from, so you write it yourself. Without <Int> the call doesn't compile.
    • length is a property. Write word.length, with no parentheses. A string's size in Kotlin is length, while a list's size is size.
    • Return type. The function declares List<Int> and returns a MutableList<Int>. That is allowed because every mutable list is also a list.
    • Boxed numbers. A List<Int> holds boxed integers on the JVM. For this size of task that makes no practical difference.

    Tracing the loop

    For ["I", "love", "pancakes"], the list after each word looks like this:

    I -> [1]
    love -> [1, 4]
    pancakes -> [1, 4, 8]

    Each pass adds exactly one number at the end, so after the loop the list has as many items as there are words. This one-in, one-out shape is common enough that Kotlin has a built-in for it, words.map { it.length }. Writing the loop first shows what map does under the hood.

    Edge cases and common mistakes

    • Uppercase letters. "Hi" has length 2, like "hi". Length counts characters, whatever their case.
    • An empty string. "" has length 0, and that 0 still goes into the result: ["Hi", ""] gives [2, 0].
    • Keeping the order. Adding to the end of the list preserves the order of words. Inserting at the front would reverse it.
    • Same length, different words. Nothing is merged: every word gets its own entry, even when two lengths are equal.

    Using the result

    The returned list always has the same size as words, which makes a quick self-check: if result.size differs from words.size, the loop added too often or too rarely. The numbers are plain Ints, so you can add them, compare them or pick the largest with the usual operators and functions.

    Testing

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