Find Words That Can Be Formed by Characters

For this easy LC problem, the solution is to first, create a map of all the characters in chars and their corresponding count or occurences. We will use occurences later on to count the available characters that can still be used.

Then, we’ll iterate through the list of words and for each of this word, we check if each character exists in chars. If it is, then decrement the count, otherwise, that particular word is invalid so don’t include it in the list of valid answers.

class Solution {
    fun countCharacters(words: Array<String>, chars: String): Int {        
        var charCount = IntArray(26)
        chars.forEach {
            charCount[it.toInt() - 97]++
        }
        
        return words.filter { word ->
            val countMap = charCount.clone()
            word.all {
                val index = it.toInt() - 97
                return@all if(countMap[index] != 0) {
                    countMap[index]--
                    true
                }else false
            }
        }.sumBy { it.length }
    }
}
Runtime: 212 ms, faster than 91.67% of Kotlin online submissions for Find Words That Can Be Formed by Characters.
Memory Usage: 35.6 MB, less than 100.00% of Kotlin online submissions for Find Words That Can Be Formed by Characters.
comments powered by Disqus