Linked List Random Node LeetCode solution in JavaScript

1
var Solution = function (head) {
2
this.res = [];
3
let curr = head;
4

5
while (curr !== null) {
6
this.res.push(curr);
7
curr = curr.next;
8
}
9
this.length = this.res.length;
10
};
11

12
Solution.prototype.getRandom = function () {
13
//Math.random() will generate a random number b/w 0 & 1.
14
//then multiply it with the array size, as i have all the value in the list, i know the size of the list
15
//take only the integer part which is a random index.
16
//return the element at that random index.
17
return this.res[Math.floor(Math.random() * this.length)].val;
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0