Longest Substring with At Least K Repeating Characters (LeetCode 395): Solution and Explanation

Medium
Hash Table
String
Divide And Conquer
Sliding Window

Given a lowercase string s and an integer k, find the length of the longest substring in which every letter appears at least k times, or 0 if there is none.

Intuition

A normal sliding window needs a rule like "growing can only break validity" so that it knows when to shrink. This problem has no such rule: adding a letter can turn an invalid window valid (a count reaches k) or a valid one invalid (a new letter appears once).

The fix is to add a constraint that does behave nicely. Decide up front that the window may hold at most target distinct letters. Growing can only push the distinct count up, so whenever it passes target you shrink from the left until it fits again.

Inside that window keep two numbers: unique, the distinct letters present, and atLeastK, how many of them already appear k times. The window is valid exactly when the two are equal.

The best answer has some number of distinct letters between 1 and 26, so one pass for each target is guaranteed to see it. That is at most 26 linear passes.

Approach: Sliding window per number of distinct letters

  1. Let best = 0. For each target from 1 to the number of distinct letters in s, run one pass.
  2. In a pass, reset 26 counts, left, unique and atLeastK to 0.
  3. Move right across the string. Add s[right]: if its count was 0, unique++; if its count becomes k, atLeastK++.
  4. While unique > target, remove s[left]: if its count was k, atLeastK--; if its count becomes 0, unique--; then left++.
  5. If unique == atLeastK, update best with right - left + 1.
  6. Return best after all passes.

Step-by-step example

s = "ababbc", k = 2
  1. Pass target = 1: windows hold one letter, like "a" or "bb". "bb" at index 3..4 is valid, best = 2.
  2. Pass target = 2: the window grows to "ababb". Once 'a' and 'b' both reach 2, unique = atLeastK = 2 and best becomes 4, then 5 at index 0..4.
  3. Adding 'c' makes 3 distinct letters, so the window drops from the left until it holds 2 again. 'c' appears once, so no later window beats 5.
  4. Pass target = 3: the window "ababbc" holds all three, but 'c' never reaches 2, so it is never valid.
  5. Return 5.

Code: Python, Java, C++

1class Solution:
2    def longestSubstring(self, s: str, k: int) -> int:
3        best = 0
4        for target in range(1, len(set(s)) + 1):
5            count = [0] * 26
6            left = unique = at_least_k = 0
7            for right in range(len(s)):
8                idx = ord(s[right]) - ord('a')
9                if count[idx] == 0:
10                    unique += 1
11                count[idx] += 1
12                if count[idx] == k:
13                    at_least_k += 1
14                while unique > target:
15                    j = ord(s[left]) - ord('a')
16                    if count[j] == k:
17                        at_least_k -= 1
18                    count[j] -= 1
19                    if count[j] == 0:
20                        unique -= 1
21                    left += 1
22                if unique == at_least_k:
23                    best = max(best, right - left + 1)
24        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(26 * n)

There are at most 26 passes and in each pass left and right each move at most n times.

Space

O(1)

Each pass uses a fixed array of 26 counts and a few integers.

Other approaches

Divide and conquer on rare letters (time O(26 * n) typical, O(n^2) worst case for naive splitting, space O(n) recursion)

Count the letters of the whole string. Any letter that appears fewer than k times can never be in a valid substring, so split the string on it and solve each piece recursively. If no letter is rare, the whole piece is valid. Short to write, but deep recursion on adversarial input.

Check every substring (time O(26 * n^2), space O(1))

For each start index, extend the end and keep 26 counts, checking validity each time. Simple and correct, but quadratic.

Common mistakes

  • Trying a single sliding window with no extra constraint. Validity is not monotonic in window size, so there is no correct moment to shrink.
  • Forgetting to decrement atLeastK when a count drops from k to k - 1 while shrinking.
  • Incrementing atLeastK when a count goes above k instead of exactly when it reaches k, which counts a letter more than once.
  • Returning a window of length 1 when k > 1. With k = 1 every non-empty string is valid, but larger k needs real repeats.

Frequently asked questions

Why is it called sliding window if we run 26 windows?

Each pass is a classic two-pointer window. The outer loop only adds a cap on distinct letters so that each window has a monotonic shrink rule. The total work is still linear times a constant.

What if k is larger than the string length?

No letter can reach k, so atLeastK stays 0 while unique is at least 1, and no window is ever valid. The answer is 0.

Which approach is better in an interview?

Both are accepted. Divide and conquer is quicker to explain; the per-target window shows you can turn a non-monotonic condition into a monotonic one, which interviewers often ask about as a follow-up.