Count subarrays with at least k fruit pairs
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithmic problem-solving focused on frequency-based counting and efficient enumeration of subarrays, testing competence in designing subquadratic solutions and selecting appropriate data representations within the Coding & Algorithms domain.
Constraints
- 0 <= nums.length <= 10^5
- 0 <= nums[i] <= 10^9
- 1 <= k <= nums.length (k may exceed the maximum achievable pairs, in which case the answer is 0)
Examples
Input: ([0, 1, 0, 1, 0], 2)
Expected Output: 3
Explanation: Qualifying subarrays: [0,1,0,1], [1,0,1,0], [0,1,0,1,0] — each has fruit 0 twice and fruit 1 twice (2 pairs).
Input: ([1, 1], 1)
Expected Output: 1
Explanation: Only [1,1] has fruit 1 appearing twice, giving 1 pair >= k.
Input: ([1, 2, 3, 4], 1)
Expected Output: 0
Explanation: All fruits are distinct, so no subarray ever forms a pair.
Input: ([], 1)
Expected Output: 0
Explanation: Empty array has no subarrays.
Input: ([5], 1)
Expected Output: 0
Explanation: A single element can never reach a frequency of 2.
Input: ([2, 2, 2], 1)
Expected Output: 3
Explanation: Subarrays [2,2] (idx 0-1), [2,2] (idx 1-2), and [2,2,2] each have fruit 2 with count >= 2, contributing one pair each.
Input: ([0, 0, 1, 1], 2)
Expected Output: 1
Explanation: Only the full array [0,0,1,1] has two distinct fruits each appearing twice, giving 2 pairs.
Input: ([3, 3, 3, 3], 2)
Expected Output: 0
Explanation: Only one fruit type exists, so the pair count can never reach 2 regardless of frequency.
Hints
- The number of pairs in a window never decreases when you extend the window to the right, and never increases when you advance the left endpoint. This monotonicity is what makes a sliding window correct.
- For a fixed right endpoint r, the valid left endpoints form a prefix [0, left-1]. Find the smallest window [left, r] that still has at least k pairs; then every start index 0..left-1 yields a qualifying subarray.
- Track 'pairs' incrementally: increment it only when a fruit's count rises to exactly 2 (extra occurrences add nothing), and decrement only when a count drops back to exactly 1 during shrinking.
- Add `left` to the running answer at each step — that is exactly how many qualifying subarrays end at index r.