Count the number of duplicated chars in a string It's an exercise, which I found on Codewars.

Instructions:

Write a function which returns the count of distinct case-insensitive alphabetic characters and numeric digits which occur more then once in a given string. The given string can be assumed to contain only alphabets (lower-, uppercase) and numerics.

Examples: 


"abcde" results in 0, because no characters repeats more than once.
"aabbcde" results in 2, because of 'a' and 'b'.
"aabBcde" => 2, because 'a' occurs twice and 'b' occurs twice (b and B).
"indivisibility" => 1, because 'i' occurs six times.
"Indivisibilities" => 2, because 'i' seven times &amp; 's' twice.
"aA11" => 2, because 'a' and '1'.
"ABBA" -> 2, because 'A' and 'B' each twice.


My (valid*) solution:

fun duplicateCount(text: String): Int {
    var count = 0
    var invalid = ArrayList&lt;Char&gt;()
    var i = 0

    while (i &lt; text.length) {
        if (invalid.contains(text[i].toLowerCase())) {
            i++
            continue
        }

        var j = i + 1

        while (j &lt; text.length) {
            if (text[i].toLowerCase() == text[j].toLowerCase()) {
                invalid.add(text[i].toLowerCase())
                count++
                break
            }
            j++
        }

        i++
    }

    return count
}


*It has passed the unit-tests.

What are your thoughts about my implementation?

How could it be improved? What would you have done differently and why?

Looking forward to reading your comments and answers.
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
}