Skip to content

Commit 648c450

Browse files
committed
Added longest repeating character solution
1 parent edb6e8c commit 648c450

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
var characterReplacement = function (s, k) {
2+
// Create two pointer to check repeating chracter (left, right)
3+
let left = 0,
4+
right = 0,
5+
maxCount = 0,
6+
map = new Map();
7+
8+
while (right < s.length) {
9+
// Save each character into map and check how many time they have
10+
map.set(s[right], map.get(s[right]) ? map.get(s[right]) + 1 : 1);
11+
maxCount = Math.max(maxCount, map.get(s[right]));
12+
13+
// Count (right-left+1-k) and compare maximum value
14+
if (right - left + 1 - k > maxCount) {
15+
// Decrement value of map[s[left]] and move left pointer
16+
map.set(s[left], map.get(s[left]) - 1);
17+
left++;
18+
}
19+
20+
right++;
21+
}
22+
23+
return right - left;
24+
};
25+
26+
// TC: O(n)
27+
// SC: O(1)

0 commit comments

Comments
 (0)