Count Good Sublists Containing N Different Integers
Given a list of integers nums and an integer n, return the number of contiguous sublists containing exactly n different integers.
A sublist is a contiguous, non-empty part of nums. A sublist is considered good when it contains exactly n distinct values.
Method Signature
int sublistsWithNDistinct(List<Integer> nums, int n)
Parameters
nums contains the integer values from which contiguous sublists are formed.
n is the required number of distinct integers in each good sublist.
Return Value
Return the total number of contiguous sublists containing exactly n distinct integers.
Constraints
1 <= nums.size() <= 20,000
1 <= nums.get(i) <= nums.size()
1 <= n <= nums.size()
Examples
Example 1
sublistsWithNDistinct(nums = [1, 2, 1, 3], n = 2)
Output: 4
The good sublists are [1, 2], [2, 1], [1, 3], and [1, 2, 1].
Example 2
sublistsWithNDistinct(nums = [4, 4, 5, 6, 5], n = 2)
Output: 5
The good sublists are [4, 5], [5, 6], [6, 5], [4, 4, 5], and [5, 6, 5].