Longest Subarray with At Most K Distinct Flavors
Arrays & HashingAuto-graded · 17 test casesLast 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) <= 20001 <= k <= len(orders)whenordersis non-empty;k >= 1always- Each flavor ID is an integer in the range
[1, 10^6] - If
len(orders) == 0, return0 - If
k >= number of distinct flavors in orders, the answer islen(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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Intuition
We want the longest contiguous window with at most k distinct values. A sliding window with two pointers (left, right) is ideal: expand to the right freely, and only shrink from the left when the constraint is violated.
Algorithm
- Maintain a frequency dictionary
freqmapping each flavor ID in the current window to its count. - Advance
rightone step at a time, addingorders[right]tofreq. - If
len(freq) > k(too many distinct flavors), incrementleft, decrementing that flavor's count infreqand deleting its entry when it reaches zero, untillen(freq) <= k. - After the shrink loop, the window
[left, right]is valid; updatebest = max(best, right - left + 1). - Return
best.
Correctness
At every iteration the window [left, right] is the longest valid window ending at right, because we only shrink the left pointer the minimum amount needed to restore validity. Taking the maximum across all right positions therefore gives the global optimum.
Edge Cases
- Empty list → return
0immediately. k >= total distinct flavors→ the while loop never fires; the answer islen(orders).- All elements identical → window always has 1 distinct flavor, answer is
len(orders).
Complexity
| Time | O(n) — each element is added and removed from freq at most once. |
| Space | O(min(n, k)) — freq holds at most k+1 entries at any moment before shrinking. |
from typing import List
def longest_at_most_k_distinct(orders: List[int], k: int) -> int:
if not orders:
return 0
freq = {}
left = 0
best = 0
for right, flavor in enumerate(orders):
freq[flavor] = freq.get(flavor, 0) + 1
# Shrink window from the left until we have at most k distinct flavors
while len(freq) > k:
left_flavor = orders[left]
freq[left_flavor] -= 1
if freq[left_flavor] == 0:
del freq[left_flavor]
left += 1
best = max(best, right - left + 1)
return best