HackerRank Solution in ES6 Javascript to Challenge: Sparse Arrays

My solution to HackerRank challenge Sparse Arrays found under Data Structures > Arrays > Sparse Arrays.

[topads][/topads]

Sparse Arrays

There is a collection of N strings ( There can be multiple occurences of a particular string ). Each string’s length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurs in the given collection of Q strings.

Input Format

The first line contains N, the number of strings.
The next N lines each contain a string.
The N + 2nd line contains Q, the number of queries.
The following Q lines each contain a query string.

Contains


1 <= N <= 1000
1 <= Q <= 1000
1 <= length of any string <= 20

Sample Input

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output

2
1
0

Explanation

Here, “aba” occurs twice, in the first and third string. The string “xzxb” occurs once in the fourth string, and “ab” does not occur at all.

[signupform][/signupform]

My Solution to this Challenge

function processData(input) {
  //Enter your code here
  const arrayInput = input.split("\n");
  const N = Number(arrayInput[0]);
  const strings = arrayInput.slice(1, N + 1);
  const queries = arrayInput.slice(N + 2);

  queries.forEach((query) => {
    const times = strings.reduce(
      (acc, string) => (query === string ? ++acc : acc),
      0
    );

    console.log(times);
  });
}

Ok, now let us digest the solution.

const arrayInput = input.split('\n');
const N = Number(arrayInput[0]);
const strings = arrayInput.slice(1, N+1);
const queries = arrayInput.slice(N+2);

We get the input and split it by the new line character (\n) and assign it to inputArray, this will give us [ ‘4’, ‘aba’, ‘baba’, ‘aba’, ‘xzxb’, ‘3’, ‘aba’, ‘xzxb’, ‘ab’ ]

Then we get the number of strings by reading the first element in inputArray and assign it to N.

Now we need to extract, from inputArray, the collection of strings to compare. Since we know the number of strings (N) we can use slice() array helper method to extract them starting at index 1 to index N+1. We get this: [‘aba’, ‘baba’, ‘aba’, ‘xzxb’].

Finally we need the queries. We get them from inputArray and since we know the queries start at N + 2 we extract them from the array starting at index N+2 to the end of the array.

Note: We use slice() method on the array because it returns a new array without modifying the original one.

queries.forEach((query) => {
  const times = strings.reduce(
    (acc, string) => (query === string ? ++acc : acc),
    0
  );

  console.log(times);
});

Using the forEach array helper method, we loop over the queries, then we compare each query to each string contained in the strings array. To accomplish this we use the reduce() array helper method. reduce() takes in two values, accumulator (or total) and the current value, then we do the actual comparison of the query and the string, if they are equal, then we increment the accumulator and return it, otherwhise we just return the accumulator.

Finally we print the number of times each query appears in the array of strings.

Note: If you are not familiar with how the reduce() method works, head over to MDN to read more about it.

Bonus!!

After some more thinking, a figured I could also use the filter() method instead of reduce() for this solution, so here it is

queries.forEach((query) => {
  const times = strings.filter((string) => string === query).length;
  console.log(times);
});

With filter() we filter out the strings array and only returning the strings that match the current query. Then we get the length of this new array, which would be how many times each query appears in the strings array.


You can play with this code in my CodePen Pen.

Open this challenge in HackerRank.

If you liked this article, show some love by sharing it!!

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.