#K38972. Shortest Gem Collection Subarray

    ID: 26317 Type: Default 1000ms 256MiB

Shortest Gem Collection Subarray

Shortest Gem Collection Subarray

You are given a sequence of gems represented by integers, where each integer denotes a color. Your task is to determine the length of the shortest contiguous subarray that contains at least one gem of each color from 1 to m. If it is not possible to collect all m colors in any contiguous subarray, output \(-1\).

Input Constraints:

  • Each test case starts with two integers: n (the number of gems) and m (the number of distinct colors required).
  • The next line contains n integers representing the colors of the gems.

Problem Overview:

For each test case, you need to compute the minimum length \(L\) of any subarray such that the subarray contains all m distinct colors at least once. Use a sliding window technique to efficiently determine the answer. If no valid subarray exists, output \(-1\).

inputFormat

The input is read from standard input (stdin) in the following format:

  1. The first line contains an integer \(T\), the number of test cases.
  2. For each test case:
    1. The first line contains two integers \(n\) and \(m\) separated by a space.
    2. The second line contains \(n\) space-separated integers representing the colors of the gems.

outputFormat

For each test case, output a single integer on a new line representing the length of the shortest contiguous subarray that contains all \(m\) colors. If no such subarray exists, output \(-1\).

## sample
3
7 4
1 2 3 1 4 2 3
5 3
1 2 3 4 5
6 3
1 1 1 1 1 1
4

3 -1

</p>