Walk a sequence and count occurrences of each value in a map. Classic "get current count, add one, write back" loop.

Algorithm

Basic Implementation

basic.kt
fun main() {
	val words = arrayOf("fig", "apple", "fig", "pear", "apple", "fig")
	val counts = HashMap<String, Int>()
	val order = mutableListOf<String>()
	for (i in words.indices) {
		val word = words[i]
		if (!counts.containsKey(word)) {
			order.add(word)
			counts[word] = 1
		} else {
			val prev = counts[word]!!
			counts[word] = prev + 1
		}
	}
	print("{")
	for (i in order.indices) {
		if (i > 0) {
			print(", ")
		}
		val key = order[i]
		print("$key: ${counts[key]}")
	}
	println("}")
}

The pinned input is [fig, apple, fig, pear, apple, fig]. The diagrams show get-or-default, writeback, and final bucket contents.

Step 1 - First write creates a key

fig is absent, so get-or-default reads 0 and writes fig: 1.

After reading the first word fig.wordold countnew countmapfig01{fig: 1}

Step 2 - Existing keys increment

The second fig reads 1 and writes 2; apple has its own count.

After fig, apple, fig.scanfigapplepearafter fig100after apple110after fig210

Step 3 - Final counts

The full scan produces fig: 3, apple: 2, and pear: 1.

Final map for [fig, apple, fig, pear, apple, fig].bucket/keycountfig3apple2pear1

Complexity

  • Time: O(n) average with HashMap<String, Int>.
  • Space: O(k) where k is the number of distinct keys.

Implementation notes

  • Kotlin: val counts = HashMap<String, Int>() is the idiomatic map; the counts.containsKey(word) predicate plus an explicit assignment keeps the lesson on the read-or-default path without hiding it behind getOrDefault or getOrPut.
  • The auxiliary order list preserves first-seen order so the final printout is deterministic — HashMap iteration order is not a contract you can rely on.
  • The replay renders the map as a list of key/value rows in first-seen order and animates the count increment on each frame.
get-or-default A first-time `word` triggers the "default" branch: append to `order` and set `counts[word] = 1`. A repeat read-modify-writes `counts[word] = prev + 1`.
first-seen order Keys are tracked in `order` (a `MutableList<String>`) to keep the printout deterministic; the `HashMap` iteration order is not a contract.