Skip to content
Problem 395 · LeetCode 395(opens in a new tab)

Longest Substring with At Least K Repeating Characters

MediumDivide and conquer

You are given a string s of lowercase letters and a number k. Look for substrings (unbroken runs of s) in which every letter that appears, appears at least k times.

Return the length of the longest such substring, or 0 if there is none.

Example 1

Input:  s = "baabcb", k = 2
Output: 4
Why:    "baab" has two b and two a; anything with the c fails
2 more examples and the constraints

Example 2

Input:  s = "ppqpq", k = 2
Output: 5
Why:    p appears 3 times and q 2 times in the whole string

Example 3

Input:  s = "abc", k = 2
Output: 0
Why:    every letter appears once

Constraints

  • 1 ≤ length of s ≤ 10,000
  • s has only lowercase English letters
  • 1 ≤ k ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every substringO(n²)
  2. Divide and conquerO(26 · n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 lettersVerdict
Every substringO(n²)
Mention it, then move on
Divide and conquerO(26 · n)
Best; cut at the short letters

n = length of s; 26 is the number of different letters.

Edge cases to test

  • k = 1. Every letter qualifies, so the answer is the whole length.
  • k bigger than the string. No substring can have k copies of anything: 0.
  • No letter appears k times. "abc" with k = 2: every letter is a wall, so every piece is empty and the answer is 0.
  • The best part is not at the start. "aabxbbbccc" with k = 2: after the cut at x, the right piece "bbbccc" gives 6.

Common mistakes

  • Using a plain sliding window: adding a letter can break the condition and later fix it, so you cannot decide when to shrink.
  • Cutting only at the first short letter and recursing deeply, which can blow the call stack on long inputs.
  • Returning the range length before checking that every letter, not just the first, reaches k.

How to talk through it

  1. 1Clarify. Lowercase only? Does every letter in the substring need k copies, or only some? What if nothing qualifies?
  2. 2Give the brute force. Check every substring with running counts; O(n²), too slow for 10,000 letters.
  3. 3Find the wall. A letter with fewer than k copies in a range can never be in the answer, so it splits the range.
  4. 4Code the recursion. Count, cut at every short letter, recurse on the pieces; say why the depth is at most 26.
  5. 5Test out loud. Run "baabcb" with k = 2, then k = 1 and a k bigger than the string.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?