#C6919. Shortest Subsequence with K Colors
Shortest Subsequence with K Colors
Shortest Subsequence with K Colors
You are given an integer n representing the number of elements, an integer k representing the total distinct colors to be present, and a list of n integers representing the colors. Your task is to find the length of the shortest contiguous subsequence (subarray) that contains all of the k colors.
If it is impossible to obtain such a subsequence, output -1
.
This problem can be efficiently solved using the sliding window technique, in which you dynamically adjust the start and end pointers while maintaining a count of the distinct colors using a hash table or an array. The answer should be computed by scanning the list only once.
inputFormat
The input is provided via stdin and consists of two lines:
- The first line contains two space-separated integers:
n
(the number of colors) andk
(the number of distinct colors required). - The second line contains
n
space-separated integers, representing the colors.
outputFormat
Output a single integer to stdout representing the length of the shortest contiguous subsequence that contains all k colors. If no such subsequence exists, output -1
.
10 3
1 2 2 3 1 2 1 3 2 3
3