← Questions
Count subarrays with at least k equal pairs
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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
kbe 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, advanceleftwhile[left, r]still has at leastkpairs; then the subarrays starting at0 .. left - 1and ending atrall qualify, so addleft. - 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,
klarger than possible.
Follow-ups
- Count pairs of indices instead: a value appearing
ctimes contributesc·(c-1)/2pairs. What changes in the update? - Count subarrays with exactly
kpairs (at leastkminus at leastk + 1). - Return the shortest subarray with at least
kpairs.
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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
