Skip to content

Commit 29ec6d3

Browse files
authored
minimum window substring solution
1 parent e9e655f commit 29ec6d3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
fun minWindow(s: String, t: String): String { // T(m, n) = S(m, n) = O(m + n)
3+
val counterT = (
4+
t
5+
.groupingBy {it} // O(n)
6+
.eachCount()
7+
)
8+
var l = -1
9+
var r = -1
10+
val counterS = mutableMapOf<Char, Int>()
11+
var i = -1
12+
(
13+
s
14+
.withIndex()
15+
.forEach { // O(m)
16+
counterS.compute(it.value) {k, v -> if (v == null) 1 else v + 1}
17+
while (i != it.index && counterS[s[i + 1]]!! > counterT.getOrDefault(s[i + 1], 0)) { // O(m)
18+
counterS.compute(s[++i]) {k, v -> v!! - 1}
19+
}
20+
if (
21+
counterT
22+
.all {(k, v) -> counterS.getOrDefault(k, 0) >= v} // O(n)
23+
) {
24+
if (r == -1 || r - l > it.index - i) {
25+
l = i
26+
r = it.index
27+
}
28+
}
29+
}
30+
)
31+
return s.substring(l + 1, r + 1) // O(m)
32+
}
33+
}

0 commit comments

Comments
 (0)