sundeepblue
3/20/2014 - 12:23 AM

Let s be an array of strings. Write function to find the distance of any closest pair of equal entries. Eg., if s = ["All", "word", "and", "

Let s be an array of strings. Write function to find the distance of any closest pair of equal entries. Eg., if s = ["All", "word", "and", "no", "play", "makes", "for", "no", "work", "no", "fun"], then the 2nd and 3rd occurrences of "no" is the closest pair.

int find_nearest_repeatition(const vector<string> &s) {
    map<string, int> hash;
    int min_dist = INT_MAX;
    for(int i=0; i<s.size(); i++) {
        if(hash.find(s[i]) != hash.end())
            min_dist = min(min_dist, i - hash[s[i]]);
        hash[s[i]] = i;
    }
    return min_dist;
}