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
- Create an empty buffer. A
valnamedresultholds ascala.collection.mutable.ArrayBuffer[String]. The full package path is written out, so no import is needed. - Loop over the words with
for (word <- words). - Test the length.
word.length > nis true only for words with more thanncharacters. - Append the word with
+=. - Return the buffer as a list. The method's return type is
List[String], soresult.toListconverts 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:
valwith a changeable buffer.valmeansresultalways refers to the same buffer; it does not make the buffer read-only. AnArrayBuffercan grow, which is why+=works on it.- Why a buffer and not a
List. AListis 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. toListcopies. The returnedListis 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, soresult.toListalone would do. The explicitreturnis correct too.- Arrays versus lists.
wordsis anArray, 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:
| word | length | buffer afterwards |
|---|---|---|
| apple | 5 | ArrayBuffer(apple) |
| kiwi | 4 | ArrayBuffer(apple) |
| banana | 6 | ArrayBuffer(apple, banana) |
| fig | 3 | ArrayBuffer(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 exactlyncharacters. For "kiwi" andn = 4it would wrongly returnList(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, soArray("cat", "dog")comes back whole.- Deduplicating. Repeated words must stay; don't use a set.
Testing
Array("apple", "kiwi", "banana", "fig"),n = 4givesList(apple, banana).Array("hi", "to", "be"),n = 3givesList().Array("go", "went", "gone", "went"),n = 3givesList(went, gone, went).Array("cat", "dog"),n = 0givesList(cat, dog).
