← Questions

Count subarrays with at least k equal pairs

0
UberCodingLast asked Sep 2025

A coding interview question asked in Uber's online assessment, last asked Sep 2025. It tests sliding window and hash maps.

You get an integer array nums, where each value is a type of fruit, and an integer k. In a subarray, a fruit type forms a pair if it appears at least twice; each type counts as at most one pair, however many times it appears. Return the number of contiguous subarrays with at least k pairs. The answer must beat O(n²).

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_subarrays(nums: list[int], k: int) -> int.

Example

count_subarrays([0, 1, 0, 1, 0], 2)  ->  3   # [0,1,0,1], [1,0,1,0], [0,1,0,1,0]
count_subarrays([1, 1], 1)           ->  1
count_subarrays([2, 2, 2, 3], 1)     ->  5   # every subarray holding at least two 2s
count_subarrays([1, 2, 3], 1)        ->  0

Constraints

  • 0 <= len(nums) <= 10^5, 0 <= nums[i] <= 10^9, 1 <= k <= len(nums).
  • The answer can exceed 32 bits.

Clarifying questions

  • Does a fruit that appears three or four times count as one pair or more? (One.)
  • Subarrays are contiguous?
  • Can k be larger than any subarray can reach?

What a strong answer covers

  • Monotonicity: extending a subarray never lowers its pair count, and dropping elements from the left never raises it.
  • A sliding window: for each right end r, advance left while [left, r] still has at least k pairs; then the subarrays starting at 0 .. left - 1 and ending at r all qualify, so add left.
  • Updating the pair count in O(1): increment when a type's count reaches exactly 2, decrement when it drops back to 1.
  • O(n) time with a hash map of counts; 64-bit total.
  • Tests: no pairs possible, all equal values, k larger than possible.

Follow-ups

  • Count pairs of indices instead: a value appearing c times contributes c·(c-1)/2 pairs. What changes in the update?
  • Count subarrays with exactly k pairs (at least k minus at least k + 1).
  • Return the shortest subarray with at least k pairs.

Where it's asked

  • Uber · Online assessment · Last asked Sep 202590 min · Two problems on a HackerRank-based platform, camera and screen share on · No AI

What it tests

sliding window · hash maps

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding