Menu
Coddy logo textTech

Frequency Maps

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 8 of 63.

A frequency map stores how often each item occurs. For each input, read its current count or zero and write back one more. This combines safe lookup, mutable assignment and iteration.

Inside main:

val counts = mutableMapOf<String, Int>()
for (word in listOf("red", "blue", "red")) {
    counts[word] = (counts[word] ?: 0) + 1
}
println(counts["red"])

The red count is inserted as one, then updated to two.

A missing frequency starts at zero before the current occurrence is added.

challenge icon

Challenge

Medium

Complete wordFrequency with parameters words: List<String>, target: String. Build a frequency map and return how often target occurs. Matching is case-sensitive.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun wordFrequency(words: List<String>, target: String): Int {
    // Write your solution here.
    return 0
}
fun main() {
    val wordsCount = readln().toInt()
    val words = mutableListOf<String>()
    for (i0 in 0 until wordsCount) {
        val wordsItem = readLine().orEmpty()
        words.add(wordsItem)
    }
    val target = readLine().orEmpty()
    println(wordFrequency(words, target))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground