FastPrepCount Subarrays with at Least K Equal-Fruit Pairs

Count Subarrays with at Least K Equal-Fruit Pairs

TikTok logoTikTok● MediumNEW GRADINTERNOA

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) → long

Examples

Example 1

fruits = [1,1,2,2]k = 2return = 1

Only the complete subarray contains one pair of 1s and one pair of 2s.

Example 2

fruits = [1,1,1,1]k = 1return = 6

Every 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 = 3

The 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 = 1

Only 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 = 4

The 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^5
  • 0 <= fruits[i] <= 10^9
  • 1 <= k <= floor(fruits.length / 2)

Source note: TikTok CodeSignal source screenshot for the fruit-pair subarray task.

More TikTok problems

See TikTok hiring insights
Saved
public long countFruitPairSubarrays(int[] fruits, int k) {
  // write your code here
}
Checking account…