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
๐ŸŽช Exclusive Club Event: Minimum 3 members per typeMembers: VIP(3) Regular(4) Student(2) Premium(4)VIPCount: 3โœ“RegularCount: 4โœ“StudentCount: 2โœ—PremiumCount: 4โœ“๐Ÿ”„ Division Process:Split HereGroup 1: VIP + RegularValid Group (Size: 7)Group 2: PremiumValid Group (Size: 4)๐Ÿ† Largest Valid GroupVIP + Regular = 7 membersMaximum sustainable event size
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.
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
58.0K Views
Medium-High Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen