Menu Close

Find the minimum number of flats, monkey needs to visit to catch ninjas

Monkey B., the young coach of Ninjas, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.

There is exactly one Ninja of some type in each of these flats. Monkey B. asked residents of the house to let him enter their flats in order to catch Ninjas. After consulting the residents of the house decided to let Monkey B. enter one flat from the street, visit several flats and then go out from some flat. But they won’t let him visit the same flat more than once.

Monkey B. was very pleased, and now he wants to visit as few flats as possible in order to collect Ninjas of all types that appear in this house. Your task is to help him and determine the minimum number of flats he has to visit.

Input:
The first line contains the integer n () — the number of flats in the house.

The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Ninja, which is in the flat number i.


Output:
Print the minimum number of flats which Monkey B. should visit in order to catch Ninjas of all types which there are in the house.

#include <stdio.h>
#define N 100000
int good(int n,int *kk){
  int c,k;
  k=0;
  for(c=0;c<52;c++)
  if(kk[c]>0)
  k++;
return k==n;
}
int f(char c){
 return c >='a'&& c<='z'?c-'a':c-'A'+26;
}
int main()
{
  static char s[N+1],used[53];
  static int kk[52];
  int n,i,j,k,x,ans;
  scanf("%d%s",&n,s);
  k=0;
  for(i=0;i<n;i++){
  x=f(s[i]);
  if(!used[x]){
  k++;
  used[x]=1;
  }
  }
  ans=n+1;
  for(i=j=0;i<n;i++){
  while(j<n&&!good(k,kk))
  kk[f(s[j++])]++;
  if(good(k,kk)&&ans>j-i)
  ans=j-i;
  kk[f(s[i])]--;
  }
  printf("%d\n",ans);
return 0;
}


INPUT_1:
6
aaBCCe

OUTPUT:
5


INPUT_2:
7
bcAAcbc

OUTPUT:
3


INPUT_3:
5
AAbce

OUTPUT:
4


ILLUSTRATION:

Executed using gcc terminal

Morae Q!