Start learning free

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

Long Words Only in Kotlin: Filtering with a Loop

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in Kotlin, explained

    Problem overview

    The function longWords receives an array of strings, words, and an Int, n. It returns a list 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 when no word is long enough the result is an empty list.

    For words = ["apple", "kiwi", "banana", "fig"] and n = 4, the result is [apple, banana]. kiwi has exactly 4 characters, so it fails the test, and fig has only 3.

    Approach: collect what passes

    The result can have any length from zero to words.size, so it can't be a fixed-size array created up front. A growing list fits: start with an empty one, look at each word once, and append the word when it passes the test. Because the loop visits the words from first to last and each one is appended at the end, the order of words is kept without any extra work.

    Step by step

    1. Create the empty list. mutableListOf<String>() makes a list that can grow, and the type argument says it holds strings. Store it in a val: the variable will always refer to this one list, and that is fine, because adding items changes the list, not the variable.
    2. Loop over the words. for (word in words) gives each element of the array in turn.
    3. Test the length. word.length > n is true only for words strictly longer than n. With >=, kiwi would be kept in the first example.
    4. Add the passing word to the list inside the if.
    5. Return the list after the loop, not inside it. If nothing passed, it is still empty, and an empty list is the right answer.

    The solution in Kotlin

    class Solution {
        fun longWords(words: Array<String>, n: Int): List<String> {
            val result = mutableListOf<String>()
            for (word in words) {
                if (word.length > n) {
                    result.add(word)
                }
            }
            return result
        }
    }
    

    Kotlin details worth knowing:

    • Mutable inside, read-only outside. mutableListOf returns a MutableList, which is also a List, so returning it matches the declared return type List<String>. The caller sees a list it can read but not change through that type.
    • val versus var. val result can't be pointed at another list later. result.add(word) never does that, so no var is needed.
    • Array versus list. The parameter is an Array<String>, and the result is a List<String>. The for loop reads either one in the same way.
    • Length counts characters of the string. word.length is the number of UTF-16 units in the string, which for lowercase English letters is the number of letters.

    Edge cases and common mistakes

    • Exactly n characters. With ["kiwi"] and n = 4 the result is empty, because the rule is "longer than", not "at least".
    • n = 0. Every word has at least one letter, so every word is kept.
    • Repeated words. ["go", "went", "gone", "went"] with n = 3 gives [went, gone, went]: nothing removes duplicates, and each occurrence is tested on its own.
    • Returning too early. A return inside the loop would stop at the first long word.

    Testing

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