Problem
Given a strings and an integer k, return the length of the longest substring of s that contains at most k distinct characters*.
Examples
Constraints
1 <= s.length <= 5 * 10^40 <= k <= 50
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 340 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 340 # by problem number
lcpy gen -s longest_substring_with_at_most_k_distinct_characters # by problem name
s and an integer k, return the length of the longest substring of s that contains at most k distinct characters*.
Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.
Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" with length 2.
1 <= s.length <= 5 * 10^40 <= k <= 50class Solution:
# Time: O(n) — each character enters and leaves the window once
# Space: O(k) — counter holds at most k + 1 distinct characters
def length_of_longest_substring_k_distinct(self, s: str, k: int) -> int:
if k == 0:
return 0
counts: dict[str, int] = {}
left = 0
best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
while len(counts) > k:
left_ch = s[left]
counts[left_ch] -= 1
if counts[left_ch] == 0:
del counts[left_ch]
left += 1
best = max(best, right - left + 1)
return best
| Time | Space |
|---|---|
| O(n) — each character enters and leaves the window once | O(k) — counter holds at most k + 1 distinct characters |