Hash Tables: Ice Cream Parlor

Problem Statement :

Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they pool their money to buy ice cream. On any given day, the parlor offers a line of flavors. Each flavor has a cost associated with it.

Given the value of money and the cost  of each flavor for  trips to the Ice Cream Parlor, help Sunny and Johnny choose two distinct flavors such that they spend their entire pool of money during each visit. ID numbers are the 1- based index number associated with a cost. For each trip to the parlor, print the ID numbers for the two types of ice cream that Sunny and Johnny purchase as two space-separated integers on a new line. You must print the smaller ID first and the larger ID second.


Two ice creams having unique IDs  and  may have the same cost (i.e. cost[ i ] = cost[ j ]  ).
There will always be a unique solution.
Function Description

Complete the function whatFlavors in the editor below. It must determine the two flavors they will purchase and print them as two space-separated integers on a line.

whatFlavors has the following parameter(s):

cost: an array of integers representing price for a flavor
money: an integer representing the amount of money they have to spend
Input Format

The first line contains an integer, t , the number of trips to the ice cream parlor.

Each of the next t sets of 3 lines is as follows:

The first line contains money.
The second line contains an integer, n, the size of the array cost.
The third line contains n space-separated integers denoting the cost[ i ].

Output Format

Print two space-separated integers denoting the respective indices for the two distinct flavors they choose to purchase in ascending order. Recall that each ice cream flavor has a unique ID number in the inclusive range from 1 to cost.

Sample Input

1 4 5 3 2
2 2 4 3
Sample Output

1 4
1 2

Solution :


                            Solution in C :

In  C :

#include <stdio.h>

int main(int argc, const char * argv[]) {
    int t;
    //printf("Enter number of trips to the ice cream parlor:\n");
    scanf("%d", &t);
    for (int trip = 0; trip < t; trip++) {
        int m;
        //printf("Enter amount of dollars:\n");
        scanf("%d", &m);
        int n;
        //printf("Enter number of flavors:\n");
        scanf("%d", &n);
        int cost[n];
        for (int id = 0; id < n; id++) {
            //printf("Enter the cost of flavor %d", id);
            scanf("%d", &cost[id]);
        int total = 0;
        for (int cost1 = 0; cost1 < n; cost1++) {
            for (int cost2 = cost1 + 1; cost2 < n; cost2++) {
                total = cost[cost1] + cost[cost2];
                if (total == m && cost1 < cost2) {
                    printf("%d %d\n", cost1 + 1, cost2 + 1);
            if (total == m) {

                        Solution in C++ :

In   C++ :

#include <bits/stdc++.h>
using namespace std;

class IceCream {
        int flavor; 
        int index;

        IceCream(int flavor, int index) {
            this->flavor = flavor;
            this->index = index;
int binarySearch(int first, int last, vector<IceCream> arr, int search) {
    int n = last;
    int mid = (first+last)/2;
    while(first <= last){
            return arr[mid].index;
                last = mid-1;
                first = mid+1;
        mid = (first+last)/2; 
    return -1; 

bool compare(IceCream i1, IceCream i2)
            return (i1.flavor < i2.flavor);

int main() {
    int t;
    int n, m;
    cin >> t;
    for(int test = 0; test < t; test++) {       
        cin >> m >> n;
        vector<IceCream> arr;

        for (int i = 0; i < n; i++) {
            int cost;
            cin >> cost;
            arr.push_back(IceCream(cost, i + 1));

        sort(arr.begin(), arr.end(), compare);
        /*for (int i = 0; i < n; i++) {
        int firstIndex = 100000, secondIndex = 100000;
        for(int i = 0; i < n - 1 ; i++) {
            int search = m - arr[i].flavor;
            if(search >= arr[i].flavor) {
                int index = binarySearch( i + 1, n - 1, arr, search);
                if( index != -1 ) {
                    cout << min(arr[i].index, index) << " " << max(arr[i].index, index) << endl;




                        Solution in Java :

In  Java :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        int t;
        int n, m;
        Scanner in = new Scanner(System.in);
        t = in.nextInt();
        HashMap<Integer, Integer> h = new HashMap<>();
       for(int test = 0; test < t; test++) {
            m = in.nextInt();
            n = in.nextInt(); 
           int first=-99999999;
           int last=-99999999;
            for (int i = 0; i < n; i++)
                int r=in.nextInt();
                   //   System.out.println("contains key "+r);
                     first= Math.min(h.get(m-r),i+1);
                        last = Math.max(h.get(m-r),i+1);
            System.out.println(first+" "+last);

                        Solution in Python : 
In  Python3   :

def flavors(m,a):
    prices = {}
    for idx, p in enumerate(a):
        if m-p in prices:
            return prices[m-p], idx
        prices[p] = idx
    return None

t = int(input().strip())
for a0 in range(t):
    m = int(input().strip())
    n = int(input().strip())
    a = list(map(int, input().strip().split(' ')))
    f1, f2 = flavors(m,a)
    print(f1+1, f2+1)

View More Similar Problems


This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →