Skip to content
RED SAGSkills

Longest Span With K Distinct Products

A checkout log lists product ids in the order they were scanned. Return the length of the longest contiguous stretch of the log that contains at most k distinct product ids.

Example 1

Input: items = [1, 2, 1, 2, 3], k = 2
Output: 4
Explanation: The stretch [1, 2, 1, 2] has two distinct ids.

Example 2

Input: items = [1, 2, 3, 4], k = 1
Output: 1

Constraints

  • 0 <= items.length <= 10^5
  • 1 <= k <= 10^5
  • 0 <= items[i] <= 10^9
Hint 1

Grow a window to the right and count ids inside it.

Hint 2

When the window holds more than k distinct ids, shrink it from the left.

Good practice for: Data Scientist, Data Engineer, Machine Learning Engineer, AI Engineer (LLM & Generative AI), Backend Developer, Full Stack Developer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.