#include<bits/stdc++.h>
using namespace std;
#define fo(i,start,end) for(int i=start;i<end;i++)
class Solution {
public:
    int minimumDistance(vector<int>& nums) {
        /*Brute Force
        Take 3 Pointers (i,j,k) 
            for each i, move j and k to find 3 elements that are same
            o(n^3) time complexity not feasible
        */
        // element -> {freq,lastSeenIndex(vector)}
        // 1 -> {vector or instances}
        //{1,2,1,1,3}
        int n = nums.size();
        int result = INT_MAX;
        unordered_map<int,vector<int>>mp; //element -> freq
        fo(it,0,n){
            mp[nums[it]].push_back(it); //increment the frequency
            if(mp[nums[it]].size() >= 3){
              vector<int>& myValues = mp[nums[it]];
               int s = myValues.size();
               // Grab the 3 MOST RECENT indices (not always 0, 1, and 2)
               int first = myValues[s - 3];
               int second = myValues[s - 2];
               int third = myValues[s - 1];
                result =   min(result,(abs(first-second) +  abs(second-third) + abs(third - first))); 
            }

            
        }
        if(result == INT_MAX)  return -1;
        else return result;
       
        //if nothing is found
    }
};
int main(){
	vector<int>arr = {1,2,1,1,3};
	Solution s;
	int ans = s.minimumDistance(arr);
	cout<<ans<<endl;
	
}