#K64162. Shortest Subarray with at Least K Distinct Integers
Shortest Subarray with at Least K Distinct Integers
Shortest Subarray with at Least K Distinct Integers
You are given an array of n integers and an integer k. Your task is to determine the length of the shortest contiguous subarray that contains at least $k$ distinct integers. If no such subarray exists, output -1
.
Note: The value k can be any integer. Use efficient algorithms to avoid timeout on larger inputs.
The problem can be formally stated as follows:
Given an array A of length n and an integer k, find the minimal length L such that there exists an index i and j with 0 ≤ i ≤ j < n for which the subarray A[i...j] contains at least $k$ distinct numbers. If no such L exists, print -1
.
inputFormat
The input is provided via standard input (stdin) and has the following format:
n k A0 A1 ... An-1
Where:
- n is the number of elements in the array.
- k is the minimum number of distinct integers required in the subarray.
- The second line contains n space-separated integers representing the array.
outputFormat
The output is a single integer printed to standard output (stdout). This integer is the length of the shortest contiguous subarray that contains at least $k$ distinct integers. If no valid subarray exists, output -1
.
7 3
1 2 1 2 3 4 5
3