Compare Strings by Frequency of the Smallest Character

This easy problem looks intimidating at first because the description looks complicated but when you analyze it further, the solution is actually straightforward.

class Solution {
    
    val score: (String) -> Int = {
        val charList = it.toList().sorted()
        if(charList.size == 1) 1 else {
            var ctr = 1
            while(ctr < charList.size && charList[ctr] == charList[ctr-1]){
                ctr++
            }
            
            ctr
        }        
    }
    
    fun numSmallerByFrequency(queries: Array<String>, words: Array<String>): IntArray {
        var wordsScore = IntArray(words.size)
        words.forEachIndexed { index, i ->
            wordsScore[index] = score(i)
        }
        
        return queries.map {
            val queryScore = score(it)
            var sum = 0
            for(i in 0 until wordsScore.size){
                sum += if(queryScore < wordsScore[i]) 1 else 0
            }
            sum
        }.toIntArray()
    }
}
Runtime: 316 ms, faster than 36.84% of Kotlin online submissions for Compare Strings by Frequency of the Smallest Character.
Memory Usage: 41.5 MB, less than 100.00% of Kotlin online submissions for Compare Strings by Frequency of the Smallest Character.

First, calculate the scores of each of the word in words. Then for each query, calculate the query score and compare it to each of the calculated words score. Then collect each result in an array.

comments powered by Disqus