fork download
  1. #include <iostream>
  2. using namespace std;
  3. #include<vector>
  4. #include <bits/stdc++.h>
  5.  
  6. int main() {
  7. // your code goes here
  8.  
  9. vector<int>arr={2,1,4,3,2,1,1,4};
  10. int n=arr.size();
  11. int l,r;
  12. cin>>l>>r;
  13. int shortest_length=INT_MAX;
  14. int current_length;
  15. int i=0,j=0;
  16. unordered_map<int,int>mp;
  17. while(i<n && j<n)
  18. {
  19.  
  20. if(arr[j]>=l && arr[j]<=r)
  21. {
  22. mp[arr[j]]++;
  23. }
  24.  
  25. if(mp.size()==abs(r-l+1))
  26. {
  27. shortest_length=min(shortest_length,abs(j-i+1));
  28.  
  29.  
  30.  
  31. if(arr[i]>=l && arr[i]<=r)
  32. {
  33. mp[arr[i]]--;
  34. if(mp[arr[i]]==0)
  35. {
  36. mp.erase(arr[i]);
  37. }
  38.  
  39. }
  40. i++;
  41. if(arr[j]>=l && arr[j]<=r)
  42. {
  43. mp[arr[j]]--;
  44. }
  45.  
  46. }
  47.  
  48. else
  49. {
  50. j++;
  51. }
  52.  
  53.  
  54. }
  55.  
  56. if(shortest_length==INT_MAX)
  57. {
  58. cout<<-1;
  59.  
  60. }
  61. else
  62. {
  63. cout<<shortest_length;
  64. }
  65.  
  66.  
  67.  
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 5296KB
stdin
2 
4
stdout
3