LeetCode 340, Medium. Topics: Hash Table, String, Sliding Window. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:
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
Constraints
1 <= s.length <= 5 * 10^4
0 <= k <= 50
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026