Longest Substring with At Least K Repeating Characters — LeetCode 395 Python Solution

MediumHash TableStringDivide and ConquerSliding Window
Problem
#395
Reading time
4 min

The 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.

Example

Input
s = "aaabb", k = 3
Output
3
Explanation
The longest substring is "aaa", as 'a' is repeated 3 times.

Python solution

Python
class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        def dfs(l, r):
            cnt = Counter(s[l : r + 1])
            split = next((c for c, v in cnt.items() if v < k), '')
            if not split:
                return r - l + 1
            i = l
            ans = 0
            while i <= r:
                while i <= r and s[i] == split:
                    i += 1
                if i >= r:
                    break
                j = i
                while j <= r and s[j] != split:
                    j += 1
                t = dfs(i, j - 1)
                ans = max(ans, t)
                i = j
            return ans

        return dfs(0, len(s) - 1)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 395. Longest Substring with At Least K Repeating Characters is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 395. Longest Substring with At Least K Repeating Characters?
LeetCode 395. Longest Substring with At Least K Repeating Characters is rated Medium on LeetCode.
What is the time complexity of LeetCode 395. Longest Substring with At Least K Repeating Characters?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 395. Longest Substring with At Least K Repeating Characters?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 395. Longest Substring with At Least K Repeating Characters cover?
LeetCode 395. Longest Substring with At Least K Repeating Characters is tagged Hash Table, String, Divide and Conquer and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview