Python 0395.py
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
# too short
if len(s) < k:
return 0
pos = defaultdict(list)
for i, c in enumerate(s):
pos[c].append(i)
skip = []
for p in pos:
if len(pos[p]) < k:
skip += pos[p]
# all letters appear often enough
if not skip:
return len(s)
# no letter appears often enough
if len(skip) == len(s):
return 0
# subdivide
result = 0
left = 0
for right in sorted(skip) + [ ]:
result = max(result, self.longestSubstring(s[left : right], k))
left = right + 1
# final segment
result = max(result, self.longestSubstring(s[left:], k))
return result
Difficulty
and has an acceptance rate of about 47% (600k+ submissions).
Typical patterns to solve this problem:
- Divide And Conquer
- Hash Table
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic “longest substring with at least k repeating characters” problem by recursively partitioning the input string around characters that cannot satisfy the frequency requirement. The algorithm first records the indices of each character, identifies the positions of characters whose total count is below k, and then uses those positions as split points. Each resulting segment is processed recursively, and the maximum length among all valid segments is returned.
Key Steps
Early termination for short strings
The function begins by checking whether the whole string is shorter than the required repetition count. If the length of the input string is less than k, no substring can meet the condition, and the function returns zero.
if len(s) < k:
return 0
Building character position map
A dictionary that maps each character to a list of its indices is constructed. The use of a defaultdict(list) allows indices to be appended without explicit existence checks, resulting in concise code and constant-time insertion per character.
pos = defaultdict(list)
for i, c in enumerate(s):
pos[c].append(i)
Determining split positions
Characters whose total occurrence count is smaller than k are identified. All indices belonging to such characters are collected into a single list named skip. This list represents the positions that must break any candidate substring, because any substring containing one of these characters would automatically violate the frequency rule.
skip = []
for p in pos:
if len(pos[p]) < k:
skip += pos[p]
Handling trivial cases after split detection
Two quick returns handle scenarios where no split is required or where every character is a splitter. If skip is empty, every character already satisfies the frequency condition, so the entire string length is the answer. Conversely, if the number of split positions equals the length of the string, no valid substring exists, and the function returns zero.
if not skip:
return len(s)
if len(skip) == len(s):
return 0
Recursive subdivision
The core of the algorithm iterates over the sorted split positions. For each interval between consecutive split points, a recursive call evaluates the longest valid substring within that interval. The variable left tracks the start of the current segment, while right denotes the next split index. After processing all explicit splits, a final recursive call handles the trailing segment after the last split.
result = 0
left = 0
for right in sorted(skip) + []:
result = max(result, self.longestSubstring(s[left : right], k))
left = right + 1
result = max(result, self.longestSubstring(s[left:], k))
Returning the best length
After all recursive branches have been explored, the function returns the maximum length found across all segments.
return result
Edge Cases Addressed
The code explicitly guards against three edge conditions:
- When the input string is shorter than the required repetition count, it returns zero without further processing.
- When every character in the string appears at least k times, the algorithm bypasses recursion entirely and returns the full length.
- When every character fails the frequency test, the algorithm detects that the split list covers the whole string and returns zero immediately.
These checks prevent unnecessary recursion and ensure correct results for extreme inputs such as an empty string, a string of uniform characters, or a string where no character meets the threshold.
Performance Optimizations
The implementation leverages several techniques to keep the execution efficient:
- Single pass index collection - By populating the position map in one linear scan, the algorithm avoids repeated counting of characters during recursion.
- Early exits - The immediate returns for the “all good” and “all bad” scenarios eliminate the need for deeper recursive calls in cases where the answer is already known.
- Sorted split positions - Sorting the
skiplist once before the subdivision loop ensures that each segment is processed in order, avoiding repeated scans for split detection inside recursive calls. - Minimal substring creation - The recursive calls use slicing (
s[left : right]ands[left:]) which, in Python, creates new string objects only for the necessary segments, keeping memory usage proportional to the size of the processed fragments rather than the entire original string at each level. - Reuse of the same function - By calling the same method recursively, the code benefits from Python’s call stack management without introducing additional helper structures, reducing overhead.
These choices collectively lead to a solution that scales well with input size, focusing work only on portions of the string that have a chance of satisfying the frequency constraint.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful magnetic letters on the refrigerator. You want to find the longest part of that string where every single letter shows up at least a certain number of times.
First, the code looks at the whole row of letters to see if it is even long enough to play the game. If there are fewer letters than the number you need, it simply stops.
Next, it acts like a busy librarian. It goes through every letter and writes down exactly where each one is sitting in the row. This helps to see which letters are popular because they show up many times, and which ones are lonely because they do not show up enough.
The code then makes a list of all those lonely letters that do not appear enough times. If there are no lonely letters, it means the whole row is perfect, so the answer is the total length of the row. If every single letter is lonely, there is no good part to find at all.
When there are some lonely letters scattered around, the code uses them like scissors. It cuts the long row into smaller pieces everywhere it finds a lonely letter. These little pieces are now separated by the gaps where the lonely letters used to be.
Finally, it repeats the exact same steps for each of those smaller pieces it just created. It keeps breaking them down until it finds the best parts that meet the rule, and it keeps track of which one of those parts is the longest of them all.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | C# | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | C# | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2014: Longest Subsequence Repeated k Times
- problem 2958: Length of Longest Subarray With at Most K Frequency
- problem 2981: Find Longest Special Substring That Occurs Thrice I
- problem 2982: Find Longest Special Substring That Occurs Thrice II
Solved On The Same Day
- problem 2558: Take Gifts From the Richest Pile
- problem 932: Beautiful Array
- problem 1382: Balance a Binary Search Tree
- problem 1424: Diagonal Traverse II
- problem 2406: Divide Intervals Into Minimum Number of Groups
- problem 2593: Find Score of an Array After Marking All Elements
- problem 2611: Mice and Cheese
- problem 2679: Sum in a Matrix
- problem 493: Reverse Pairs
- problem 2551: Put Marbles in Bags
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality