#395

Longest Substring with At Least K Repeating Characters

Medium
Hash TableStringDivide and ConquerSliding WindowHash MapDivide and Conquer
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a recursive approach that divides the string based on the characters that do not meet the frequency requirement. This allows us to efficiently find the longest valid substring by breaking the problem down into smaller parts.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in the string.
  2. 2Step 2: Identify characters that occur less than k times; if none, return the length of the string.
  3. 3Step 3: Split the string at these characters and recursively find the longest valid substring in each part.
solution.py13 lines
1# Full working Python code
2
3def longestSubstring(s, k):
4    from collections import Counter
5    freq = Counter(s)
6    for char in freq:
7        if freq[char] < k:
8            return max(longestSubstring(sub, k) for sub in s.split(char))
9    return len(s)
10
11# Example usage
12print(longestSubstring('aaabb', 3))  # Output: 3
13print(longestSubstring('ababbc', 2))  # Output: 5

Complexity note: The time complexity is O(n) because we only traverse the string a limited number of times. The space complexity is O(n) due to the storage of character frequencies and the potential substrings created during the split.

  • 1Identifying characters that do not meet the frequency requirement allows for efficient substring splitting.
  • 2Recursive approaches can simplify complex problems by breaking them down into manageable parts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.