Skip to content

Commit b09f25b

Browse files
committed
✔️ add solution for Dynamic Array problem.
1 parent 51d8180 commit b09f25b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
|:---------------------------:|:----------------------------------------------------------------------------------------------------------------------------:|:------:|:----------:|:-------------------------------------------------------------------------------------------------:|
3535
| Arrays | [Arrays - DS](https://www.hackerrank.com/challenges/arrays-ds) | 10 | Easy | [solution.js](arrays/arrays-ds.js) |
3636
| Arrays | [Left Rotation](https://www.hackerrank.com/challenges/array-left-rotation) | 20 | Easy | [solution.js](arrays/left-rotation.js) |
37+
| Arrays | [Left Rotation](https://www.hackerrank.com/challenges/dynamic-array) | 15 | Easy | [solution.js](arrays/dynamic-array.js) |
3738

3839
## 👤 Author
3940

Diff for: arrays/dynamic-array.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Problem: https://www.hackerrank.com/challenges/dynamic-array/problem
2+
3+
function dynamicArray(n, queries) {
4+
// Declare a 2-dimensional array, *arr*, of *n* empty arrays. All arrays are zero indexed.
5+
let arr = [];
6+
for (let i = 0; i < n; i++) {
7+
arr.push([]);
8+
}
9+
// Declare an integer, lastAnswer, and initialize it to 0.
10+
let lastAnswer = 0;
11+
// Declare an array for store the new values of lastAnswer
12+
let lastAnswers = [];
13+
14+
for(let j=0; j<queries.length; j++) {
15+
let queryType = queries[j][0];
16+
let x = queries[j][1];
17+
let y = queries[j][2];
18+
19+
let idx = ((x ^ lastAnswer) % n);
20+
21+
// Query: 1 x y
22+
if( queryType == '1') {
23+
arr[idx].push(y);
24+
}
25+
// Query: 2 x y
26+
else {
27+
lastAnswer = arr[idx][ y % arr[idx].length];
28+
lastAnswers.push(lastAnswer);
29+
}
30+
}
31+
32+
return lastAnswers;
33+
}
34+
35+
// test 1
36+
let t1Size = 2;
37+
let t1Array = new Array(new Array(1, 0, 5), new Array(1, 1, 7), new Array(1, 0, 3), new Array(2, 1, 0 ), new Array(2, 1, 1 ));
38+
39+
let t1Result = dynamicArray(t1Size, t1Array);
40+
console.log(t1Result);

0 commit comments

Comments
 (0)