LeetCode 395: Longest substring with AtLeast K Repeating characters
Given a string
s
and an integerk
, return the length of the longest substring ofs
such that the frequency of each character in this substring is greater than or equal tok
.
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/
Since we need to deal with contiguous array only sliding window method makes sense here.
function longestSubstring(s, k) {
//your code
}
first we need to have a hashmap to store all the count of letters
for (let i = 0; i < s.length; i++) {
// hash[s[i]] = hash[s[i]] ? ++hash[s[i]] : 1
if (!(s[i] in hash)) {
hash[s[i]] = 0;
}
hash[s[i]]++;
}
now the best case scenario should be handled, that is when all the chars of the hash table has the count≥k we need to return that length;
if (Object.values(hash).every((val) => val >= k)) return s.length;
Now let think.
We need to traverse through the list, but need to stop when we encounter a letter that doesn’t has k counts. We split from the current_start position and up to the current position+1.