Count Subarrays with at Least K Equal-Fruit Pairs
Problem statement
You are given an integer array fruits and an integer k. A pair consists of two equal fruit values, and each array position may belong to at most one pair.
For a subarray, a fruit value that appears count times contributes floor(count / 2) disjoint pairs. Return the number of contiguous subarrays whose total number of pairs across all fruit values is at least k.
Function
countFruitPairSubarrays(fruits: int[], k: int) → longExamples
Example 1
fruits = [1,1,2,2]k = 2return = 1Only the complete subarray contains one pair of 1s and one pair of 2s.
Example 2
fruits = [1,1,1,1]k = 1return = 6Every subarray of length at least two contains a pair. There are 3 + 2 + 1 = 6 such subarrays.
Example 3
fruits = [0,1,0,1,0]k = 2return = 3The qualifying subarrays are indices [0..3], [1..4], and [0..4]. Each contains at least two disjoint equal-fruit pairs.
Example 4
fruits = [2,2,2,2,2,2]k = 3return = 1Only the whole subarray [0..5] has six fruits, so it can form three disjoint pairs. Every shorter subarray has at most two pairs.
Example 5
fruits = [1,3,3,1]k = 1return = 4The four qualifying subarrays are [0..2], [0..3], [1..2], and [1..3]. Each contains the two 3s. The whole subarray also contains the two 1s; it is still counted only once.
Constraints
2 <= fruits.length <= 10^50 <= fruits[i] <= 10^91 <= k <= floor(fruits.length / 2)
Source note: TikTok CodeSignal source screenshot for the fruit-pair subarray task.