Hacker Rank Solutions in PHP - Day 08 - Dictionaries and Maps

30 Days of Code - Day 08 - Dictionaries and Maps

Task

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.

Note: Your phone book should be a Dictionary/Map/HashMap data structure.


Solution in PHP:

You can implement this phone book using a PHP associative array (dictionary). Here's a sample code for reading and processing the input to create the phone book and then querying it:

<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */

$phoneBook = [];

// Read the number of entries
$n = intval(fgets($_fp));

// Populate the phone book
for ($i = 0; $i < $n; $i++) {
   $entry = explode(" ", trim(fgets($_fp)));
   $name = $entry[0];
   $phoneNumber = $entry[1];
   $phoneBook[$name] = $phoneNumber;
}

// Query the phone book
while (!feof($_fp)) {
   $queryName = trim(fgets($_fp));
   if (isset($phoneBook[$queryName])) {
      echo $queryName . "=" . $phoneBook[$queryName] . PHP_EOL;
   } else {
      echo "Not found" . PHP_EOL;
   }
}

fclose($_fp);

?>

This code reads the number of entries, populates the phone book, and then queries it for names. If a name is found, it prints the associated phone number; otherwise, it prints "Not found."

Press ESC to close