Longest Substring with At Most K Distinct Characters — LeetCode 340 Python Solution
MediumLeetCode PremiumHash TableStringSliding Window
- Problem
- #340
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Example
- Input
- s = "eceba", k = 2
- Output
- 3
- Explanation
- The substring is "ece" with length 3.
Python solution
Python
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
l = 0
cnt = Counter()
for c in s:
cnt[c] += 1
if len(cnt) > k:
cnt[s[l]] -= 1
if cnt[s[l]] == 0:
del cnt[s[l]]
l += 1
return len(s) - lComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(k) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 340. Longest Substring with At Most K Distinct 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
LeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 424Longest Repeating Character ReplacementMedium
Frequently asked questions
- How hard is LeetCode 340. Longest Substring with At Most K Distinct Characters?
- LeetCode 340. Longest Substring with At Most K Distinct Characters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 340. Longest Substring with At Most K Distinct Characters?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 340. Longest Substring with At Most K Distinct Characters?
- The Python solution on this page uses O(k) auxiliary space.
- What topics does LeetCode 340. Longest Substring with At Most K Distinct Characters cover?
- LeetCode 340. Longest Substring with At Most K Distinct Characters is tagged Hash Table, String and Sliding Window on LeetCode.
- Is LeetCode 340. Longest Substring with At Most K Distinct Characters a premium problem?
- Yes. LeetCode 340. Longest Substring with At Most K Distinct Characters is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.