Cracking the Coding Interview: Binary Search – Ice Cream Parlor

Here’s my solution to the challenge: https://www.hackerrank.com/challenges/ctci-ice-cream-parlor

int indexOf(vector arr, int value, int excludeThis) {
    for(int i = 1; i <= arr.size(); i++) {
        if(arr[i - 1] == value && i != excludeThis) {
            return i;
        }
    }
    return -1;
}

int* getIndicesFromValues(vector arr, int value1, int value2) {
    int index1 = indexOf(arr, value1, -1);
    int index2 = indexOf(arr, value2, index1);
    int* indices = new int[2];
    *(indices) = min(index1, index2);
    *(indices + 1) = max(index1, index2);
    return indices;
}

void solve(vector  arr, int money) {
    vector sortedArr = arr;
    int n = sortedArr.size();
    sort(sortedArr.begin(), sortedArr.begin() + n);
    for(int i = 0; i < n; i++) {
        int complement = money - sortedArr[i];
        vector::iterator lower = lower_bound(sortedArr.begin() + 1, sortedArr.end(), complement);
        if(*lower == complement) {
            int* indices = getIndicesFromValues(arr, sortedArr[i], complement);
            cout << *indices << " " << *(indices + 1) << endl;
            break;
        }
    }
}

All my solutions to HackerRank challenges can be found here: https://github.com/sdulaney/hackerrank

Leave a Comment