Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Count runs with exactly k distinct values

Hard · Target 30 minutes · Sliding window· Type asked at

Given an array nums and an integer k, return the number of contiguous subarrays that contain exactly k distinct values.

Examples

InputOutputWhy
nums = [1,2,1,2,3], k = 27[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
nums = [1,2,1,3,4], k = 33[1,2,1,3], [2,1,3], [1,3,4].
nums = [3,3,3], k = 20

Constraints

  • 1 ≤ n ≤ 2 × 10⁴
  • 1 ≤ k ≤ n
  • 1 ≤ nums[i] ≤ n

Hints

Hint 1

Try the usual window: shrink while there are more than k values. Why does adding hi − lo + 1 overcount?

Hint 2

"At most k distinct" survives shrinking, so it can be counted with one window. Can you express "exactly k" through it?

Hint 3

Exactly k = (at most k) − (at most k − 1). Write atMost once and call it twice.

Where people lose marks

  • Using one window and adding hi − lo + 1: that counts at most k, not exactly k.
  • atMost(0) must return 0; write the function so the empty window is handled without a special case.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.