Skip to content

Commit 8b4cc71

Browse files
committed
Add Longest Uniform Substring After Replacements
1 parent 903e7b4 commit 8b4cc71

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
fun longestUniformSubstringAfterReplacements(s: String, k: Int): Int {
2+
val freqs = mutableMapOf<Char, Int>()
3+
var highestFreq = 0
4+
var maxLen = 0
5+
var left = 0
6+
var right = 0
7+
while (right < s.length) {
8+
// Update the frequency of the character at the right pointer
9+
// and the highest frequency for the current window.
10+
freqs[s[right]] = freqs.getOrDefault(s[right], 0) + 1
11+
highestFreq = maxOf(highestFreq, freqs[s[right]]!!)
12+
// Calculate replacements needed for the current window.
13+
val numCharsToReplace = (right - left + 1) - highestFreq
14+
// Slide the window if the number of replacements needed exceeds
15+
// 'k'. The right pointer always gets advanced, so we just need
16+
// to advance 'left'.
17+
if (numCharsToReplace > k) {
18+
// Remove the character at the left pointer from the hash map
19+
// before advancing the left pointer.
20+
freqs[s[left]] = freqs[s[left]]!! - 1
21+
left++
22+
}
23+
// Since the length of the current window increases or stays the
24+
// same, assign the length of the current window to 'maxLen'.
25+
maxLen = right - left + 1
26+
// Expand the window.
27+
right++
28+
}
29+
return maxLen
30+
}

0 commit comments

Comments
 (0)