All problems
0554MediumHash TableStringSliding Window

Longest Belt Run Within a Colour Budget

Tracked in this browser only
Write code

Trains the technique from

LeetCode 340Longest Substring with At Most K Distinct Characters

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def length_of_longest_substring_k_distinct(s: str, k: int) -> int:
Java
public int lengthOfLongestSubstringKDistinct(String s, int k)
September 7
Apply