← DiffPush

Subarrays with K Different Integers

DiffPush Tier Sliding Window · Hard Problems O(n) · O(n)

The Multi-Tenant Bandwidth Tally

A colocation facility logs which tenant (as an integer id) consumed each hourly slot. A billing window is 'mixed' when exactly k distinct tenants appear in it. Finance wants the number of mixed windows. The tally trick: count windows with at most k tenants, subtract windows with at most k-1, and the difference is exactly the mixed set.

Input: An integer array nums of tenant ids and an integer k.

Output: Return the number of contiguous subarrays containing exactly k distinct values.

Constraints

Examples

Example 1

Input: {"nums":[1,2,1,2,3],"k":2}
Output: 7
Seven windows use exactly the tenant pairs {1,2} or {2,3}.

Example 2

Input: {"nums":[1,2,1,3,4],"k":3}
Output: 3
Only the windows reaching tenant 4's neighborhood carry three distinct ids.

Solve this in your browser →

Also on LeetCode ↗