Skip to content

Instantly share code, notes, and snippets.

@ExpandingShapes
Created October 12, 2021 13:07
Show Gist options
  • Save ExpandingShapes/3a8ee501a91c09e5696dffb35ef411e7 to your computer and use it in GitHub Desktop.
Save ExpandingShapes/3a8ee501a91c09e5696dffb35ef411e7 to your computer and use it in GitHub Desktop.
we are given two strings text and pattern of size n and m respectively where m < n. Our task is to find all the indices in text where anagrams of pattern are found.
private fun findIndices(text: String, pattern: String): List<Int> {
val n = text.length
val m = pattern.length
val indices: MutableList<Int> = ArrayList()
// Frequency arrays - assuming we have a set of 256 characters
val textCount = IntArray(256)
val patternCount = IntArray(256)
// Loop until m
for (i in 0 until m) {
textCount[text[i].toInt()]++
patternCount[pattern[i].toInt()]++
}
// At this point, we have traversed m characters in both the arrays.
// Now we will loop through the remaining characters
for (i in m until n) {
// Check if the counts of characters in frequency arrays are equal or not
if (isCountEqual(textCount, patternCount)) {
indices.add(i - m)
}
// Discard left most character
textCount[text[i - m].toInt()]--
// Include current character
textCount[text[i].toInt()]++
}
// Check for the last window
if (isCountEqual(textCount, patternCount)) {
indices.add(n - m)
}
return indices
}
private fun isCountEqual(textCount: IntArray, patternCount: IntArray): Boolean {
for (i in 0..255) {
if (textCount[i] != patternCount[i]) {
return false
}
}
return true
}
fun main() {
println("Anagrams are found at: " + findIndices("BACDGABCDA", "ABCD"))
println("Anagrams are found at: " + findIndices("XYYZXZYZXXYZ", "XYZ"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment