April 14, 2021 Andrey

Sparse Arrays – Hackerrank medium problem in JS solved using HashMap

https://www.hackerrank.com/challenges/sparse-arrays/problem

The idea is to iterate over input data and put it into HashMap with keys being available strings and values being the number of times this string is present in the input.

Time complexity is O(n) and space complexity O(n)


function matchingStrings(strings, queries) {
    
    let hashMap = new Map();
    
    for (let i = 0; i < strings.length; i++) {
        if (hashMap.has(strings[i])) {
            hashMap.set(strings[i], hashMap.get(strings[i]) + 1);
        } else {
            hashMap.set(strings[i], 1);
        }
    }
    
    let result = [];
    for (let i = 0; i < queries.length; i++) {
         if (hashMap.has(queries[i])) {
             result.push(hashMap.get(queries[i]));
         } else {
             result.push(0);
         }
         
    }
    
    return result;
}