HackerRank Dictionaries and Maps | JS Solution

HackerRank Dictionaries and Maps | JS Solution

Problem

HackerRank detailed problem description can be found here.

Inputs & Outputs

/*
input {string} '3\nsam 99912222\ntom 11122222\nharry 12299933\nsam\nedward\nharry'
  - 1st line: `n` number of entries in the phone book
  - `n` lines: `name phoneNumber` 2 space-separated values on a single line
  - unknown number of lines: `name` queries

output {string} 'key=value' or 'Not found'
*/

Test Case

input = '3\nsam 99912222\ntom 11122222\nharry 12299933\nsam\nedward\nharry';

Pseudocode

  1. Let's first validate the input
  2. Then, process that input, so that we have 3 data points separated: 1) number of entries in the phone book, 2) entries, and 3) queries
  3. Next, let's create an object representation of the phone book with all of the provided entries phoneBookObj
  4. Lastly, we go ahead and run through the queries to see if they exist in our phone book and either output the query in 'key=value' format or 'Not found'

JavaScript Solution

function processData(input) {
  if (!input || typeof input !== 'string') {
    throw new Error('`input` must be a `string` data type');
  }

  let arr = input.split('\n');
  let entriesArr = arr.slice(1, parseInt(arr[0]) + 1);
  let queriesArr = arr.slice(parseInt(arr[0]) + 1);
  let phoneBookObj = {};

  entriesArr.forEach(contact => {
    let entry = contact.split(' ');
    phoneBookObj[entry[0]] = entry[1];
  })

  queriesArr.forEach(query => {
    if (phoneBookObj[query]) {
      console.log(`${query}=${phoneBookObj[query]}`);
    } else {
      console.log('Not found');
    }
  })

  // console.log('entriesArr: ', entriesArr);
  // console.log('queriesArr: ', queriesArr);
  // console.log('phoneBookObj: ', phoneBookObj);
};

Here are some test logs that show what our variables created above look like:

entriesArr:  [ 'sam 99912222', 'tom 11122222', 'harry 12299933' ]
queriesArr:  [ 'sam', 'edward', 'harry' ]
phoneBookObj:  { sam: '99912222', tom: '11122222', harry: '12299933' }

Resources

  1. Dictionaries and Maps algorithm by HackerRank
  2. .split(), .slice() and .forEach() methods by MDN Web Docs
  3. parseInt() function by MDN Web Docs