Count Complete Substrings - Sliding Window [JS]
Solution: Sliding Window
There can be up to 26
unique characters in a substring, and each character occurs exactly k
times.
For each number of unique characters, maintain a sliding window of characters where
- The difference between two adjacent characters is at most
2
. - The length of the window doesn't exceed the size the substring is meant to be:
unique characters * k
.
Count the number of substrings with exactlyunique
unique characters which occurk
times each.
Time Complexity: O(26n)
Space Complexity: O(1)
var countCompleteSubstrings = function(word, k) {
let n = word.length, complete = 0;
for (let unique = 1; unique <= 26; unique++) {
let substrSize = unique * k;
let charsWithKFreq = 0;
let count = Array(26).fill(0);
for (let j = 0, i = 0; j < n; j++) {
// diff between adjacent chars > 2, reset the window completely
if (j > 0 && diff(word[j], word[j - 1]) > 2) {
count = Array(26).fill(0);
charsWithKFreq = 0;
i = j;
}
count[word.charCodeAt(j) - 97]++;
if (count[word.charCodeAt(j) - 97] === k) charsWithKFreq++;
// move left pointer up while window is too big for the substring size
while (j - i + 1 > substrSize) {
if (count[word.charCodeAt(i) - 97] === k) charsWithKFreq--;
count[word.charCodeAt(i) - 97]--;
i++;
}
if (charsWithKFreq === unique) complete++;
}
}
return complete;
};
function diff(a, b) {
return Math.abs(a.charCodeAt() - b.charCodeAt());
}
Comments
Post a Comment