Longest Substring with At Least K Repeating Characters - Problem
You are given a string s and an integer k. Your task is to find the length of the longest substring where every character appears at least k times.
Think of it as finding the most "balanced" part of the string where no character is underrepresented. For example, in the string "aaabbb" with k=2, both 'a' and 'b' appear 3 times, so the entire string qualifies. However, in "ababbc" with k=2, the character 'c' only appears once, so we need to find substrings that exclude it.
Return the length of the longest valid substring, or 0 if no such substring exists.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aaabb", k = 3
โบ
Output:
3
๐ก Note:
The longest substring is "aaa" where 'a' appears 3 times, which satisfies k=3. The substring "bb" only has 'b' appearing 2 times, which is less than k=3.
example_2.py โ No Valid Substring
$
Input:
s = "ababbc", k = 2
โบ
Output:
5
๐ก Note:
The longest substring is "ababb" where both 'a' and 'b' appear at least 2 times (a:2, b:3). The character 'c' only appears once, so it cannot be part of any valid substring.
example_3.py โ Entire String Valid
$
Input:
s = "aaabbb", k = 3
โบ
Output:
6
๐ก Note:
The entire string is valid because both 'a' and 'b' appear exactly 3 times, which meets the requirement k=3.
Constraints
- 1 โค s.length โค 104
- s consists of only lowercase English letters
- 1 โค k โค 105
- Note: k can be larger than the string length
Visualization
Tap to expand
Understanding the Visualization
1
Survey All Members
Count how many members of each type are available for the event
2
Identify Exclusions
Mark member types that don't meet the minimum requirement as invalid
3
Divide Groups
Split the member list around invalid types, creating separate valid groups
4
Optimize Each Group
Recursively find the largest valid group within each segment
Key Takeaway
๐ฏ Key Insight: Characters that don't meet the frequency requirement act as natural dividers, allowing us to solve smaller subproblems independently and find the optimal solution efficiently.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code