10
Feb
2020

Hackerrank Minimum Distances (C++)

C++ :

int minimumDistances(vector<int> a) {
    int dist = -1, maxInt = 2147483647, minDist = maxInt;

    for(int i = 0; i < a.size(); i++){
        for(int j = i + 1; j <= a.size() -1; j++){
            if(a[i] == a[j]){
                dist = j - i;
                cout << "dist: " << dist << endl;
                if(dist < minDist){
                    minDist = dist;
                }
            }
        }
    }

    if(minDist == maxInt){
        minDist = -1;
    }

    return minDist;
}

Explanation:

First, assign a large number to maxInt and assign it to minDist. In this case, we use the largest possible int, 2,147,483,647. Using a double nested for loop, loop through the vector a, setting i initially to 0 and j initially to i + 1. If a[i] is equal to a[j], find the dist between a[i] and a[j] using j – i, and set it to dist.

Next, compare dist to minDist, if dist is smaller than minDist, set minDist to dist. Outside the for loop, if no matching numbers are found, which means minDist would still be the same as maxInt, set minDist to -1 (no matching integers found).

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *