Hash Tables: Ice Cream Parlor

Sort by

recency

|

668 Discussions

|

  • + 0 comments

    C++ Solution

    void whatFlavors(vector<int> cost, int money) 
    {
        map<int, int> hash;
        for(int i = 0; i < cost.size(); i++)
        {
            int remaining_money = money - cost[i];
            if(remaining_money <= 0) continue; // cant buy a second flavor so continues
            if(hash[remaining_money] > 0) //if it exists
            {
                cout << hash[remaining_money] << " " << i + 1 << endl;
                return;
            }
            hash[cost[i]] = i + 1;
        }
    }
    
  • + 0 comments

    Python3

    def whatFlavors(cost, money):
        mapping = {}
        
        for i in range(len(cost)):
            current_price = cost[i]
            if current_price in mapping.keys():
                if mapping[current_price] < i + 1:
                    # Print complement price index first
                    print("{} {}".format(mapping[current_price], i + 1))
                else:
                    print("{} {}".format(i + 1, mapping[cost[i]]))
            # Map current price index to complement price
            mapping[money - current_price] = i + 1
    
  • + 0 comments
    from collections import defaultdict
    def whatFlavors(cost, money):
        # Write your code here
        cache = defaultdict(list)
        for idx, c in enumerate(cost, 1):
            if l := cache[money-c]:
                print(l[0], idx)
                return
            cache[c].append(idx)
    
  • + 0 comments

    include

    void findIceCream(int money, int n, int cost[]) { int i, j; for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (cost[i] + cost[j] == money) { printf("%d %d\n", i + 1, j + 1); // 1-based index return; } } } }

    int main() { int t; scanf("%d", &t); // Number of trips

    while (t--) {
        int money, n;
        scanf("%d %d", &money, &n); // Money and number of flavors
    
        int cost[n];
        for (int i = 0; i < n; i++) {
            scanf("%d", &cost[i]); // Cost of each flavor
        }
    
        findIceCream(money, n, cost); // Find the two distinct flavors
    }
    
    return 0;
    

    }

  • + 0 comments

    include

    void findIceCream(int money, int n, int cost[]) { int i, j; for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (cost[i] + cost[j] == money) { printf("%d %d\n", i + 1, j + 1); // 1-based index return; } } } }

    int main() { int t; scanf("%d", &t); // Number of trips

    while (t--) {
        int money, n;
        scanf("%d %d", &money, &n); // Money and number of flavors
    
        int cost[n];
        for (int i = 0; i < n; i++) {
            scanf("%d", &cost[i]); // Cost of each flavor
        }
    
        findIceCream(money, n, cost); // Find the two distinct flavors
    }
    
    return 0;
    

    }