KatInterview

Longest Subarray with At Most K Distinct Flavors

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingarrayssliding windowhash map

Last updated

Tests the classic sliding window pattern for finding the longest contiguous subarray containing at most K distinct values.

Longest Subarray with At Most K Distinct Flavors

A food truck records each customer's chosen flavor as an integer ID. You are given the sequence of orders as a list orders and a positive integer k.

Find the length of the longest contiguous subarray of orders that contains at most k distinct flavor IDs.

If orders is empty, return 0.

Constraints

  • 0 <= len(orders) <= 2000
  • 1 <= k <= len(orders) when orders is non-empty; k >= 1 always
  • Each flavor ID is an integer in the range [1, 10^6]
  • If len(orders) == 0, return 0
  • If k >= number of distinct flavors in orders, the answer is len(orders)

Examples

Example 1

Input: longest_at_most_k_distinct([1, 2, 1, 3, 2, 1], 2)

Output: 3

Example 2

Input: longest_at_most_k_distinct([5, 5, 5, 5], 1)

Output: 4

Example 3

Input: longest_at_most_k_distinct([1, 2, 3, 4, 5], 3)

Output: 3

Hints

Hint 1

Use two pointers (left and right) to maintain a window; expand right and shrink left whenever the window has more than k distinct values.

Hint 2

Keep a frequency map (dict) of flavor IDs currently in the window; remove an entry when its count drops to zero to track the number of distinct flavors in O(1).

Hint 3

Track the maximum window size seen so far and update it after every valid expansion of the right pointer.