1
var nthUglyNumber = function (n) {
2
let uglyNo = 1;
3
let uglySet = new Set(); // Set to keep track of all the ugly Numbers to stop repetition
4
uglySet.add(uglyNo);
5
let minHeap = new MinPriorityQueue(); // Javascript provides inbuilt min and max heaps, constructor does not require callback function for primitive types but a comparator callback for object data types, to know which key corresponds to the priority
6
//callback looks like this new MinPriorityQueue((bid) => bid.value)
7
// if this is confusing, check the documentation here
8
// https://github.com/datastructures-js/priority-queue/blob/master/README.md#constructor
9
while (n > 1) {
10
if (!uglySet.has(uglyNo * 2)) {
11
// add only if the set does not have this ugly no.
12
minHeap.enqueue(uglyNo * 2, uglyNo * 2); // enqueue takes two inputs element and priority respectively, both are same here
13
uglySet.add(uglyNo * 2);
14
}
15
if (!uglySet.has(uglyNo * 3)) {
16
minHeap.enqueue(uglyNo * 3, uglyNo * 3);
17
uglySet.add(uglyNo * 3);
18
}
19
if (!uglySet.has(uglyNo * 5)) {
20
minHeap.enqueue(uglyNo * 5, uglyNo * 5);
21
uglySet.add(uglyNo * 5);
22
}
23
uglyNo = minHeap.dequeue().element; //dequeue returns an object with two properties priority and element
24
n--;
25
}
26

27
return uglyNo;
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0