#K71447. Longest Subarray with Exactly K Distinct Integers

    ID: 33533 Type: Default 1000ms 256MiB

Longest Subarray with Exactly K Distinct Integers

Longest Subarray with Exactly K Distinct Integers

Given an array of n integers and an integer k, your task is to determine the length of the longest contiguous subarray that contains exactly k distinct integers.

You are required to implement a solution that uses an efficient sliding window technique. More formally, if we denote by \(f(l, r)\) the number of distinct integers in the subarray \(a_l, a_{l+1}, \ldots, a_r\), then you need to find the maximum value of \(r - l + 1\) such that \(f(l, r) = k\). If no such subarray exists, output 0.

Input: The input is read from stdin.

Output: The answer for each test case is printed to stdout.

You may assume that \(0 \leq k \leq n\) and that the array elements fit within typical integer range.

inputFormat

The first line contains an integer T indicating the number of test cases. Each test case is described as follows:

  • The first line of each test case contains two integers n and k where n is the number of elements in the array and k is the required number of distinct integers.
  • The second line contains n space-separated integers representing the array.

Input is read from standard input (stdin).

outputFormat

For each test case, print a single integer denoting the length of the longest contiguous subarray that has exactly k distinct integers. If no such subarray exists, print 0.

Each answer should be printed on a new line on standard output (stdout).

## sample
1
7 3
1 2 1 3 4 2 3
4

</p>