Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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.
if no such substring exists, return 0.
Example 1:
Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Constraints:
1 <= s.length <= 104s consists of only lowercase English letters.1 <= k <= 105Problem summary: 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. if no such substring exists, return 0.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Sliding Window
"aaabb" 3
"ababbc" 2
longest-subsequence-repeated-k-times)number-of-equal-count-substrings)optimal-partition-of-string)length-of-longest-subarray-with-at-most-k-frequency)find-longest-special-substring-that-occurs-thrice-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #395: Longest Substring with At Least K Repeating Characters
class Solution {
private String s;
private int k;
public int longestSubstring(String s, int k) {
this.s = s;
this.k = k;
return dfs(0, s.length() - 1);
}
private int dfs(int l, int r) {
int[] cnt = new int[26];
for (int i = l; i <= r; ++i) {
++cnt[s.charAt(i) - 'a'];
}
char split = 0;
for (int i = 0; i < 26; ++i) {
if (cnt[i] > 0 && cnt[i] < k) {
split = (char) (i + 'a');
break;
}
}
if (split == 0) {
return r - l + 1;
}
int i = l;
int ans = 0;
while (i <= r) {
while (i <= r && s.charAt(i) == split) {
++i;
}
if (i > r) {
break;
}
int j = i;
while (j <= r && s.charAt(j) != split) {
++j;
}
int t = dfs(i, j - 1);
ans = Math.max(ans, t);
i = j;
}
return ans;
}
}
// Accepted solution for LeetCode #395: Longest Substring with At Least K Repeating Characters
func longestSubstring(s string, k int) int {
var dfs func(l, r int) int
dfs = func(l, r int) int {
cnt := [26]int{}
for i := l; i <= r; i++ {
cnt[s[i]-'a']++
}
var split byte
for i, v := range cnt {
if v > 0 && v < k {
split = byte(i + 'a')
break
}
}
if split == 0 {
return r - l + 1
}
i := l
ans := 0
for i <= r {
for i <= r && s[i] == split {
i++
}
if i > r {
break
}
j := i
for j <= r && s[j] != split {
j++
}
t := dfs(i, j-1)
ans = max(ans, t)
i = j
}
return ans
}
return dfs(0, len(s)-1)
}
# Accepted solution for LeetCode #395: Longest Substring with At Least K Repeating Characters
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
def dfs(l, r):
cnt = Counter(s[l : r + 1])
split = next((c for c, v in cnt.items() if v < k), '')
if not split:
return r - l + 1
i = l
ans = 0
while i <= r:
while i <= r and s[i] == split:
i += 1
if i >= r:
break
j = i
while j <= r and s[j] != split:
j += 1
t = dfs(i, j - 1)
ans = max(ans, t)
i = j
return ans
return dfs(0, len(s) - 1)
// Accepted solution for LeetCode #395: Longest Substring with At Least K Repeating Characters
struct Solution;
use std::collections::HashMap;
impl Solution {
fn longest_substring(s: String, k: i32) -> i32 {
let mut hm: HashMap<char, usize> = HashMap::new();
for c in s.chars() {
*hm.entry(c).or_default() += 1;
}
for (c, v) in hm {
if v < k as usize {
return s
.split_terminator(c)
.map(|s| Self::longest_substring(s.to_string(), k))
.max()
.unwrap();
}
}
s.len() as i32
}
}
#[test]
fn test() {
let s = "aaabb".to_string();
let k = 3;
let res = 3;
assert_eq!(Solution::longest_substring(s, k), res);
let s = "ababbc".to_string();
let k = 2;
let res = 5;
assert_eq!(Solution::longest_substring(s, k), res);
let s = "ababbc".to_string();
let k = 3;
let res = 0;
assert_eq!(Solution::longest_substring(s, k), res);
}
// Accepted solution for LeetCode #395: Longest Substring with At Least K Repeating Characters
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #395: Longest Substring with At Least K Repeating Characters
// class Solution {
// private String s;
// private int k;
//
// public int longestSubstring(String s, int k) {
// this.s = s;
// this.k = k;
// return dfs(0, s.length() - 1);
// }
//
// private int dfs(int l, int r) {
// int[] cnt = new int[26];
// for (int i = l; i <= r; ++i) {
// ++cnt[s.charAt(i) - 'a'];
// }
// char split = 0;
// for (int i = 0; i < 26; ++i) {
// if (cnt[i] > 0 && cnt[i] < k) {
// split = (char) (i + 'a');
// break;
// }
// }
// if (split == 0) {
// return r - l + 1;
// }
// int i = l;
// int ans = 0;
// while (i <= r) {
// while (i <= r && s.charAt(i) == split) {
// ++i;
// }
// if (i > r) {
// break;
// }
// int j = i;
// while (j <= r && s.charAt(j) != split) {
// ++j;
// }
// int t = dfs(i, j - 1);
// ans = Math.max(ans, t);
// i = j;
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.