Python interview question: longest subarray with at most k distinct values
Problem
categories is the sequence of item categories on a conveyor belt. Return the length of the longest contiguous stretch with at most k distinct categories; an empty belt gives 0.
def longest_k_categories(categories: list[str], k: int) -> int:
Example
categories = ['bread', 'cheese', 'bread', 'tea', 'tea', 'bread', 'coffee', 'cheese'], k = 2 → 4bread, tea, tea, bread: repeats don’t add categories
Solve it free
Checked against hidden tests, right in your browser. No sign-up needed.