Created
March 16, 2021 16:16
-
-
Save yairzaslavsky/b33f933788b938e3cece206cfae05c43 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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