Longest Substring with At Most K Distinct Characters
Real-world version: Longest Belt Run Within a Colour BudgetThe statement here is our own: the same inputs, outputs and technique.
Parts travel down a belt in a fixed order, and each part carries a single-character colour code. The string s lists those codes from the first part to the last.
A packing cell can handle a stretch of consecutive parts only while that stretch uses at most k different colour codes. Return the number of parts in the longest such stretch. When k is 0 no stretch qualifies, so the answer is 0.
Examples
Example 1
- Input
- s = "abaccc", k = 2
- Output
- 4
The four parts from position 2 to position 5 carry the codes a, c, c, c, which is two different codes and so within the budget of two.
Example 2
- Input
- s = "xyxyzz", k = 1
- Output
- 2
With a budget of one code, a stretch may only hold repeats of a single code. The two parts at positions 4 and 5 both carry z, giving a run of two.
Example 3
- Input
- s = "abcdef", k = 0
- Output
- 0
A budget of zero codes admits no part at all, so the answer is 0.
Constraints
- 1 <= s.length <= 5 * 10^4
- 0 <= k <= 50
- s contains only lowercase English letters and digits.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def length_of_longest_substring_k_distinct(s: str, k: int) -> int:public int lengthOfLongestSubstringKDistinct(String s, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 14 test cases: 14 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Maximum Length Substring With Two OccurrencesReal-world version: Longest Twice-Only StretchEasy
- Substrings of Size Three with Distinct CharactersReal-world version: Three Clean Pigment WindowsEasy
- Longest Nice SubstringReal-world version: Longest Matched-Case RunEasy
- Longest Substring Without Repeating CharactersReal-world version: Largest Clean Tap BlockMedium