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
Problem Overview: Longest Substring with At Least K Repeating CharactersInput: s = "aaabb", k = 3Requirement: Each character must appear ≥ 3 timesaaabba: 3 times ✓b: 2 times ✗Valid substring: "aaa"Output: 3 (length of longest valid substring)
Understanding the Visualization
1
Input Analysis
String with character frequency requirement
2
Find Valid Substrings
Identify substrings where all chars appear ≥ k times
3
Return Length
Length of the longest valid substring
Key Takeaway
🎯 Key Insight: Characters that appear less than k times globally can never be part of a valid substring
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