LeetCode 395: Longest substring with AtLeast K Repeating characters

Adarsh Gupta
2 min readSep 1, 2024

Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.

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.

--

--

Adarsh Gupta

Software Engineer | JavaScript developer | Technical Writer . Work with me? adarshguptaworks@gmail.com Connect with me? twitter.com/adarsh____gupta/