#C10824. Smallest Subarray with At Least K Distinct Elements
Smallest Subarray with At Least K Distinct Elements
Smallest Subarray with At Least K Distinct Elements
You are given an array of integers along with an integer k. Your task is to find the length of the smallest contiguous subarray that contains at least k distinct elements. If there is no subarray satisfying this condition, output -1.
Note: The problem requires efficient scanning of the subarray using techniques such as the sliding window method. In particular, you will need to maintain a running count of distinct elements as you extend and contract the window.
The mathematical formulation for the distinct count can be expressed as follows:
Find the minimum L such that there exists indices i and j with j - i + 1 = L and
[ |{a_i, a_{i+1}, \ldots, a_j}| \geq k, ]
where \(|\cdot|\) denotes the number of distinct elements in the set.
inputFormat
The input is given via stdin and consists of two lines:
- The first line contains two space-separated integers: n (the number of elements in the array) and k (the minimum number of distinct elements required).
- The second line contains n space-separated integers representing the array elements.
It is guaranteed that n is a positive integer and k is a positive integer.
outputFormat
Output via stdout a single integer: the length of the smallest contiguous subarray that contains at least k distinct elements. If no such subarray exists, output -1
.
7 3
1 2 1 3 4 2 3
3