1320. Exactly K Twin Pairs

A museum keeps a numbered ticket log in the array nums. For any stretch of consecutive entries, its twin count is the number of index pairs i < j inside that stretch with nums[i] == nums[j]. For example, the stretch (4, 4, 4) has twin count 3 and the stretch (4, 5, 4) has twin count 1.

Return how many non-empty contiguous subarrays of nums have a twin count of exactly k. Subarrays are identified by their position, so equal stretches at different positions count separately. Both k and the answer can exceed the 32-bit range, so use 64-bit integers. Aim for O(n) expected time and O(n) extra space.

Example 1

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

Exactly one equal pair appears in (1,1) at positions 0-1, (1,1) at positions 1-2 and (1,1,2) at positions 1-3.

Example 2

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

Only the whole array has all 3 pairs of equal positions; shorter stretches have at most 1.

Example 3

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

All values are distinct, so every one of the 6 subarrays has zero pairs.

Constraints

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

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…