HackerRank Solution in ES6 Javascript to Challenge: Dynamic Array

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

[topads][/topads]

Dynamic Array

  • Create a list, seqList, of N empty sequences, where each sequence is indexed from 0 to N – 1. The elements within each of the N sequences also use 0-indexing.
  • Create an integer, lastAnswer, and initialize it to 0.
  • The 2 types of queries that can be performed on your list of sequences (seqList) are described below:
    1. Query: 1 x y
      1. Find the sequence, seq, at index ((x XOR lastAnswer)) % N) in seqList.
      2. Append integer y to sequence seq.
    2. Query: 2 x y
      1. Find the sequence, seq, at index ((x XOR lastAnswer)) % N) in seqList.
      2. Find the value of element y % size in seq (where size is the size of seq) and assign it to lastAnswer.
      3. Print the new value of lastAnswer on a new line

Task

Given N, Q, and Q queries, execute each query.

Note: bitwise XOR operation, which corresponds to the ^ operator in most languages. Learn more about it on Wikipedia.

Input Format

The first line contains two space-separated integers, N (the number of sequences) and Q (the number of queries), respectively.

Each of the Q subsequent lines contains a query in the format defined above.

Constraints

  • 1 <= N, Q <= 1010
  • 0 <= x <= 109
  • 0 <= y <= 109
  • It is guaranteed that query type 2 will never query an empty sequence or index.

Output Format

For each type 2 query, print the updated value of lastAnswer on a new line.

Sample Input

2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

Sample Output

7
3

Explanation

Initial Values:

N = 2
lastAnswer = 0
S0 = []
S1 = []

Query 0: Append 5 to sequence ((0 XOR 0) % 2) = 0

lastAnswer = 0
S0 = [5]
S1 = []

Query 1: Append 7 to sequence ((1 XOR 0) % 2) = 1

S0 = [5]
S1 = [7]

Query 2: Append 3 to sequence ((0 XOR 0) % 2) = 0

lastAnswer = 0
S0 = [5,3]
S1 = [7]

Query 3: Assign the value at index 0 of sequence ((1 XOR 0) % 2) = 1 to lastAnswer, print lastAnswer
lastAnswer = 7
S0 = [5,3]
S1 = [7]

7

Query 4: Assign the value at index 1 of sequence ((1 XOR 7) % 2) = 0 to lastAnswer, print lastAnswer

lastAnswer = 3
S0 = [5,3]
S1 = [7]

3

[signupform][/signupform]

My Solution to this Challenge

function processData(input) {
  //Enter your code here
  const S = [];
  let lastAnswer = 0;
  const inputArray = input.split("\n");
  const N = inputArray[0].split(" ")[0];

  for (let i = 0; i < N; i++) {
    S[i] = [];
  }

  inputArray.slice(1).forEach((el) => {
    const [q, x, y] = el.split(" ").map(Number);
    const seq = (x ^ lastAnswer) % N;

    switch (q) {
      case 1:
        S[seq].push(y);
        break;
      case 2:
        const size = S[seq].length;
        const index = y % size;
        lastAnswer = S[seq][index];
        console.log(lastAnswer);
        break;
    }
  });

  return S;
}

Ok, now let us digest the solution.

const S = [];
let lastAnswer = 0;
const inputArray = input.split('\n');
const N = inputArray[0].split(' ')[0]

First we declare sequences array that will hold the dynamic arrays.

Then we declare lastAnswer and assign it an initial value of 0, this will hold the last answer when we hit a query of type 2.

Since the input will come in the below format we need to split it by the new line character (\n) and assign it to inputArray.

2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

After we slit the input, inputArray will contain the new input like this: [ ‘2 5’, ‘1 0 5’, ‘1 1 7’, ‘1 0 3’, ‘2 1 0’, ‘2 1 1’ ]

We declare N to hold the number of sequences, by getting first element from our input array then getting the first number.

for(let i=0;i<N;i++) {
  S[i] = [];
}

this loop creates as many empty dynamic arrays as needed and stores them in the sequences array.

inputArray.slice(1).forEach((el) => {
  const [q, x, y] = el.split(" ").map(Number);
  const seq = (x ^ lastAnswer) % N;

  switch (q) {
    case 1:
      S[seq].push(y);
      break;
    case 2:
      const size = S[seq].length;
      const index = y % size;
      lastAnswer = S[seq][index];
      console.log(lastAnswer);
      break;
  }
});

We take the input array and pass it through the slice method to remove the first element, this will give us the following output: [ ‘1 0 5’, ‘1 1 7’, ‘1 0 3’, ‘2 1 0’, ‘2 1 1’ ].

The output from slice will be passed to forEach array helper method, where we perform the bulk of the operations. forEach loops through the elements from the input array.

Inside forEach. First we split the current element (‘1 0 5’) in the array by space, creating a new array then we convert each element to integer, giving us [1, 0, 5]. finally by using array destructuring we assing these numbers to q, x and y respectively.

Next we calculate the sequence with the given formula (((x ^ lastAnswer) % N)) and assign it to seq.

We use a switch statement to identify which query type should be calculated next.

Case 1

This one is the simplest, we just find the subarray, or sequence, then push y

Case 2

We get the length (size) of the required sequence and the index to find the specific element in the sequence.

With that information we look into the specific sequence and index to get the value for lastAnswer.

Finally we print lastAnswer. We repeat this process until we reach the last element in our input array (inputArray).


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!!


Consider giving back by getting me a coffee (or a couple) by clicking the following button:

[bottomads][/bottomads]

Spread the love

2 thoughts on “HackerRank Solution in ES6 Javascript to Challenge: Dynamic Array

  1. Ashutosh Singh says:

    This solution is not giving result as desired.

    Please check.

    • Chaz says:

      idk why print to console tends to mean return an array in hackerrank

      function dynamicArray(n, queries) {
      const S = [];
      let lastAnswer = 0;
      const answerArr = [];

      for(let i=0;i {
      const [q, x, y] = el;
      let seq;

      switch(q) {
      case 1:
      seq = ((x ^ lastAnswer) % n);
      S[seq].push(y);
      break;
      case 2:
      seq = ((x ^ lastAnswer) % n);
      const size = S[seq].length;
      const index = y % size;
      lastAnswer = S[seq][index];
      answerArr.push(lastAnswer);
      break;
      };
      });
      return answerArr;
      }

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.