Skip to content

Instantly share code, notes, and snippets.

@yairzaslavsky
Created March 16, 2021 16:16
Show Gist options
  • Save yairzaslavsky/b33f933788b938e3cece206cfae05c43 to your computer and use it in GitHub Desktop.
Save yairzaslavsky/b33f933788b938e3cece206cfae05c43 to your computer and use it in GitHub Desktop.
fun firstIndexOfNthMostFrequentChar(str: String, n: Int): Int {
val countsMap = createCountsMap(str)
if (countsMap.size < n) {
return -1
}
val sortedKeyValuePairs = sortKeyValuePairs(countsMap)
val ch = sortedKeyValuePairs[n-1].first
return str.indexOf(ch, 0)
}
fun sortKeyValuePairs(map: Map<Char, Int>): List<Pair<Char, Int>> {
val pairs: MutableList<Pair<Char, Int>> = map.toList().toMutableList()
pairs.sortBy{ -it.second }
return pairs
}
fun createCountsMap(str: String): Map<Char, Int> {
val result: MutableMap<Char, Int> = mutableMapOf()
for (ch in str) {
var count = result.getOrPut(ch, {0})
result.put(ch, ++count)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment