From 0ad22958756112e8fb25e38a2b2ba433e88a00ff Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 4 Feb 2024 21:15:56 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB76.=20Minimum=20Window=20Subs?= =?UTF-8?q?tring=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- kt/minimum-window-substring.kt | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 kt/minimum-window-substring.kt diff --git a/kt/minimum-window-substring.kt b/kt/minimum-window-substring.kt new file mode 100644 index 0000000..4a3b184 --- /dev/null +++ b/kt/minimum-window-substring.kt @@ -0,0 +1,35 @@ +class Solution { + fun minWindow(s: String, t: String): String { + val freqs = IntArray(128) { 0 } + t.forEach { + freqs[it.toInt()]++ + } + + var (bestLower, bestUpper) = 0 to -1 + var count = t.length + var (l, r) = 0 to 0 + + while (r < s.length) { + if (freqs[s[r].toInt()]-- > 0) { + count-- + } + + while (count == 0) { + if (bestLower >= bestUpper || bestUpper - bestLower + 1 > r - l + 1) { + bestLower = l + bestUpper = r + } + + freqs[s[l].toInt()]++ + + if (freqs[s[l++].toInt()] > 0) { + count++ + } + } + + r++ + } + + return s.substring(bestLower, bestUpper + 1) + } +}