Find the Nearest Repeated Entries In an Array

EPI 13.6


Description:

Given an input array of strings, find the distance between a closest pair of repeating strings.

Example:

{"All", "work", "and", "no", "play", "makes", "for", "no", "work", "no", "fun", "and"}

result should be 2, between "no" and "no"

Idea:

use hashmap, record the last index. Compare with the corrent index.

Code:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>

using namespace std;

int nearestEntry(vector<string> arr){
    unordered_map<string, int> dict;
    int minDist = INT_MAX;
    for(int i=0; i<arr.size(); i++){
        if(dict.find(arr[i]) != dict.end()){
            minDist = min(minDist, i-dict[arr[i]]);
        }
        dict[arr[i]] = i;
    }
    return minDist;
}

int main(){
    vector<string> arr={"All", "work", "and", "no", "play", "makes", "for", "no", "work", "no", "fun", "and"};
    cout<<nearestEntry(arr)<<endl;
}

results matching ""

    No results matching ""