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 JAVA (judge verdict: Wrong Answer)

import java.util.Scanner;

public class Main {
    //http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_3_A
    //http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=2692179#1 -- reference
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int K = in.nextInt();//target
        int a[] = new int[n+1];
        for(int i = 1; i<=n ;i++){
            a[i] = in.nextInt();
        }
        int tag[] = new int[K+1];
        //use two pointer
        int p1 = 0, p2 = 0;
        int min = n+1;//smallest size
        int sum = 0;
        //moving the pointer and check the sum < k
        while(p1<=n){
            //p2 = p1;
            if(sum==K) min = Math.min(min, p2-p1+1);
            //main body
            //move right pointer
            if(sum<K){
                p2++;
                if(p2>n) break;
                if(a[p2] <= K){
                    sum++;
                    tag[a[p2]]++;
                }
            }else {
                p1++;
                if(p1>n) break;
                if(a[p1]<=K){
                    tag[a[p1]]--;
                    if(tag[a[p1]]==0) sum--;
                }
            }

        }
        if(min == n+1) System.out.println(0);
        else System.out.println(min);

    }

}