1299. Exactly K Repeaters

A library log lists the ids of borrowed books, one entry after another, in the array nums. Inside any stretch of consecutive entries, call an id a repeater when it appears at least twice in that stretch. Return how many non-empty contiguous subarrays of nums contain exactly k distinct repeater ids. A value of k equal to 0 asks for stretches in which no id appears twice.

Subarrays are identified by their position, so equal stretches at different positions are counted separately. The answer can exceed the 32-bit range, so return a 64-bit integer. Aim for O(n) expected time and O(n) extra space.

Example 1

Input:
nums = [1,1,2,2,3], k = 1
Output:
6
Explanation:

Six subarrays contain exactly one repeated value: (1,1), (1,1,2), (1,2,2), (1,2,2,3), (2,2) and (2,2,3).

Example 2

Input:
nums = [5,5,5], k = 2
Output:
0
Explanation:

Only one distinct value exists, so no stretch can have two repeaters.

Example 3

Input:
nums = [1,2,3], k = 0
Output:
6
Explanation:

No value repeats anywhere, so all 6 subarrays have zero repeaters.

Constraints

  • 1 ≤ n ≤ 105, where n is the length of nums
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…