diff --git a/problems/substring-with-concatenation-of-all-words.kt b/problems/substring-with-concatenation-of-all-words.kt new file mode 100644 index 0000000..640e1f0 --- /dev/null +++ b/problems/substring-with-concatenation-of-all-words.kt @@ -0,0 +1,29 @@ +class Solution { + private fun buildTable(words: Sequence): Map { + val table = mutableMapOf() + + words.forEach { + table.put(it, 1 + table.getOrElse(it) { 0 }) + } + + return table + } + private fun buildTable(s: String, length: Int): Map = + buildTable(s.chunked(length).asSequence()) + + fun findSubstring(s: String, words: Array): List { + val expectedFrequencies = buildTable(words.asSequence()) + val wordLen = words.first().length + val windowSize = wordLen * words.size + + return s + .windowed(windowSize) + .zip(s.indices) + .filter { (window, _) -> + val frequencies = buildTable(window, wordLen) + frequencies == expectedFrequencies + } + .map { (_, idx) -> idx } + .toList() + } +}