Count the number of duplicated chars in a string
A more straight forward solution would be to count each character and then to count the characters that have a count larger than 1. This can easily be done using the functional methods available in Kotlin's standard library:

fun duplicateCount(text: String): Int =
  text.toLowerCase()
    .groupingBy { it }.eachCount()
    .count { it.value &gt; 1 }


.groupingBy { it }.eachCount() creates a map (Map&lt;Char, Int&gt;) that assigns each character in the string to its count.

.count { it.value &gt; 1 } then counts all entries in the map where the count is more than one.



EDIT: Inspired by @SimonForsberg here in comparision a procedural implementation of the same algorithm. I also modified the version above to use the better count(predicate) method, which I originally forgot about.

fun duplicateCount(text: String): Int {
    val lcText = text.toLowerCase()
    val characterCount = mutableMapOf&lt;Char, Int&gt;()

    for (i in 0 until lcText.length) {
        val char = lcText[i]
        characterCount.put(char, 1 + characterCount.getOrDefault(char, 0))
    }

    var count = 0

    for (entry in characterCount) {
        if (entry.value &gt; 1) {
            count++
        }
    }

    return count
}