In this HackerRank Day 8: Dictionaries problem solution Given n names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not found instead.

HackerRank Day 8: Dictionaries and Maps problem solution


Problem solution in Python programming.

import sys

n = int(input().strip())
phoneBook = {}

# populate phoneBook dict
for i in range(n):
    phoneName,phoneNumber = input().strip().split(' ')
    phoneBook[phoneName] = phoneNumber
    
# process test entries
#names = sys.stdin.readlines()
names = [line.rstrip() for line in sys.stdin]
for i in range(len(names)):
    if names[i] in phoneBook:
        print(names[i]+'='+phoneBook[names[i]])
    else:
        print('Not found')



Problem solution in Java programming.

//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;

class Solution{
   public static void main(String []argh)
   {
       Scanner in = new Scanner(System.in);
       int N = in.nextInt();
       
       Map<String, Integer> p = new HashMap<String, Integer>();
       
       for (int i = 0; i < N; i++) {
           String name = in.next();
           int phone = in.nextInt();
           //System.out.println(name + " : " + phone);
           p.put(name, phone);
       }
       
       while (in.hasNext()) {
           String query = in.next();
           String result = p.containsKey(query) ? query + "=" + p.get(query) : "Not found";
           System.out.println(result);
       }
   }
}




Problem solution in C++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    cin>>n;
    map<string,int> lookupMap;
    for(size_t i(0);i<n;++i)
    {
        string name;
        int num;
        cin>>name >>num;
        lookupMap[name] = num; 
    }
    string name;
    while(getline(cin,name))
    {
        if((name.size()==1 && name[0]=='\n')||name.empty())
            continue;
        if(lookupMap.find(name) == lookupMap.end())
            {
            cout<<"Not found"<<endl;
        }
        else
            {
            cout<<name<<"="<<lookupMap[name]<<endl;
        }
    }
    return 0;
}



Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define NUM_ENTRIES 10000

typedef struct _entry{
    unsigned char* name;
    unsigned long number;
    struct _entry* next;
}entry_t;


typedef struct _hash_bucket{
    entry_t* head;
    entry_t* tail;
    unsigned long size;
}hash_bucket_t;

entry_t* create_entry(unsigned char* name, unsigned int num){
    entry_t* e = calloc(1,sizeof(entry_t));
    if(e == NULL){
        return NULL;
    }else{
        e->name = malloc(strlen((char*)name)+1);
        if(e->name == NULL){
            free(e);
            return NULL;
        }
        e->number = num;
        strncpy( (char*)e->name,(char*)name,strlen((char*)name)+1);
        e->next = NULL;
    }
    return e;
}

unsigned long hash(unsigned char *str){
    unsigned long hash = 5381;
    int c;

    while ((c = *str++))
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

entry_t* insert(hash_bucket_t** table, unsigned char* name, unsigned long num){
    unsigned long idx = hash(name)%NUM_ENTRIES;
    entry_t* e = create_entry(name,num);
    if(e == NULL)
        return NULL;
    if(table[idx] == NULL){
        table[idx] = calloc(1,sizeof(hash_bucket_t));
        if(table[idx] == NULL)
            return NULL;
        table[idx]->head = e;
        table[idx]->tail = e;
        table[idx]->size = 1;
    }else{
        table[idx]->tail->next = e;
        table[idx]->size++;
        table[idx]->tail = e;
    }

    return e;
}

entry_t* find(hash_bucket_t** table, unsigned char* name){
    unsigned long idx = hash(name)%NUM_ENTRIES;
    if(table[idx] == NULL){
        return NULL;
    }
    entry_t* here = table[idx]->head;
    while(here != NULL && (strcmp((char*) here->name,(char*) name)) != 0){
        here = here->next;
    }
    return here;
}

void free_entry(entry_t* e){
    free(e->name);
    free(e);
}

void clear_table(hash_bucket_t** table){
    unsigned int i;
    for(i = 0; i<NUM_ENTRIES;i++){
        if(table[i]){
            entry_t* here = table[i]->head;
            entry_t* hold = NULL;
            while(here != NULL){
                hold = here;
                here = here->next;
                free_entry(hold);
            }
            free(table[i]);
        }
    }
    free(table);
}

hash_bucket_t** entry_table;
unsigned char buf[256];
unsigned long num_s;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    unsigned int n;
    unsigned int i;
    scanf("%ud\n",&n);
    entry_table = calloc(NUM_ENTRIES,sizeof(entry_t*));
    if(!entry_table)
        exit(-1);

    for(i = 0;i<n;i++){
        scanf("%s %lu\n",buf,&num_s);
        if(!insert(entry_table,buf,num_s)){
            printf("bad insert\n");
            exit(-1);
        }
    }
    while( scanf("%s",buf) == 1){
        entry_t* e = find(entry_table,buf);
        if(e == NULL){
            printf("Not found\n");
        }else{
            printf("%s=%lu\n",buf,e->number);
        }
    }
    scanf("%s",buf); /*throw away the extra entry */
    clear_table(entry_table);
    exit(0);
}



Problem solution in Javascript programming.

function processData(input) {
    let inputs = input.split('\n');
    let hash = {};
let N = parseInt(inputs.shift());

for(let i=0; i < N; i++){
  let entry = inputs[i].split(' ');
  hash[entry[0]] = entry[1];
}

for (let i = N; i < inputs.length; i++) {
  console.log( hash[inputs[i]] ? `${inputs[i]}=${hash[inputs[i]]}`: 'Not found' );
}

} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});