Longest Substring with At Least K Repeating Characters - Problem

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.

Note: A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "aaabb", k = 3
Output: 3
💡 Note: The longest substring is "aaa" where character 'a' appears 3 times, which meets the requirement k=3.
Example 2 — No Valid Substring
$ Input: s = "ababbc", k = 2
Output: 5
💡 Note: The longest substring is "ababb" where 'a' appears 2 times and 'b' appears 3 times, both ≥ k=2.
Example 3 — Impossible Case
$ Input: s = "abc", k = 4
Output: 0
💡 Note: No character appears 4 times since the string length is only 3, so return 0.

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of only lowercase English letters
  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Longest Substring with At Least K Repeating Characters INPUT String s = "aaabb" a a a b b 0 1 2 3 4 Character Frequency: 'a': 3 'b': 2 Input Values: s = "aaabb" k = 3 Each char must appear at least k=3 times ALGORITHM STEPS 1 Count Frequencies Count each char in string 2 Find Split Point Find char with count < k 3 Divide and Conquer Split at invalid char 4 Return Maximum Max length from substrings Splitting Process: "aaabb" "aaa" | "bb" (split at 'b', count=2 < 3) FINAL RESULT Valid Substring Found: a a a "aaa" - all chars meet k=3 Rejected: "bb" b b 'b' appears 2 times < 3 Output: 3 [OK] Length of "aaa" = 3 Key Insight: The divide-and-conquer approach splits the string at characters that appear fewer than k times. Such characters can NEVER be part of a valid substring, so we recursively solve for each part. Time Complexity: O(26*N) where 26 is alphabet size. Each recursion eliminates at least one unique char. TutorialsPoint - Longest Substring with At Least K Repeating Characters | Optimal Solution (Divide and Conquer)
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
180.5K Views
Medium Frequency
~25 min Avg. Time
3.4K 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