Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

The Smallest Window II

For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0.

Constraints

$1 \leq N \leq 10^5$

$1 \leq K \leq 10^5$

$1 \leq a_i \leq 10^5$

Input

The input is given in the following format.

$N$ $K$

$a_1$ $a_2$ ... $a_N$

Output

Print the smallest sub-array size in a line.

Sample Input 1

6 2
4 1 2 1 3 5

Sample Output 1

2

Sample Input 2

6 3
4 1 2 1 3 5

Sample Output 2

3

Sample Input 3

3 4
1 2 3

Sample Output 3

0

Solution in C++ (judge verdict: Accepted)

#include<bits/stdc++.h>
using namespace std;
int n,k,a[111111];

int solve(int m){
  int ak[111111]={};
  for(int i=0;i<n;i++){
    ak[a[i]]++;
    if(i<m-1)continue;
    int t=1;
    for(int j=1;j<=k;j++)
      if(ak[j]==0){
	t=0;
	break;
      }
    ak[a[i-(m-1)]]--;
    if(t)return 1;
  }
  return 0;
}

int main(){
  cin>>n>>k;
  int kk[111111]={},f=0;
  for(int i=0;i<n;i++)cin>>a[i],kk[a[i]]++;
  for(int i=1;i<=k;i++)if(kk[i]==0)f=1;
  int l=0,m,r=n;
  while(r-l>1){
    m=(l+r)/2;
    //cout<<solve(m)<<" "<<m<<endl;
    if(solve(m))r=m;
    else l=m;
  }
  if(f)cout<<0<<endl;
  else cout<<r<<endl;
  return 0;
}