Character Mapping

This isn’t a solution to a problem but this could be really handy when solving some problems on LC particularly when you need to create a histogram of characters in a particular string. For example, the word “leetcode” will have a histogram of:

l=1
e=3
t=1
c=1
o=1
d=1

Typically, you will need to write this code to generate the map:

val map = HashMap<Char, Int>()
"leetcode".forEach {
    map.putIfAbsent(it, 0)
    map[it] = map[it] + 1
}

But there’s a shorter and better way to do it:

val map = "leetcode".groupingBy { it }.eachCount()