> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Longest Substring with At Most K Distinct

> Tested Python solution for LeetCode 340 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 340, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Sliding Window](/catalog/topics/sliding-window). [View on LeetCode](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 340   # by problem number
lcpy gen -s longest_substring_with_at_most_k_distinct_characters   # by problem name
```

## 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\*.

### Examples

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

### Constraints

* `1 <= s.length <= 5 * 10^4`
* `0 <= k <= 50`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/longest_substring_with_at_most_k_distinct_characters/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/longest_substring_with_at_most_k_distinct_characters/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class 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
```

## Complexity

| Time | Space |
| - | - |
| O(n) — each character enters and leaves the window once | O(k) — counter holds at most k + 1 distinct characters |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.