MaxPriorityQueue is not defined
Asked Answered
D

1

8

I am experiencing something that is confusing me.

While working through problems in javascript on leetcode, I came across a solution that implemented a MaxPriorityQueue in the solution.

The posted solution was:

Finally, there's a Max/MinPriorityQueue for JavaScript!

add -> enqueue( )
remove -> dequeue( )
highest number (peek) -> front( )
.element -> actual value

var lastStoneWeight = function(stones) {
    const m = new MaxPriorityQueue()
    for(const w of stones) m.enqueue(w)
    
    while(m.size() > 1){
        const diff = m.dequeue().element - m.dequeue().element
        if(diff > 0) m.enqueue(diff)
    }
 
    return m.size() === 0 ? 0 : m.front().element
};

I tried to implement this myself in my own environment and get:

const m = new MaxPriorityQueue();
            ^

ReferenceError: MaxPriorityQueue is not defined

at lastStoneWeight (C:\Users\steph\Desktop\coding-projects\learning-js\leetcode\last-stone-weight.js:55:13)
    at Object.<anonymous> (C:\Users\steph\Desktop\coding-projects\learning-js\leetcode\last-stone-weight.js:66:13)

I went and plugged the same code into leetcode and it ran without a hitch.

I tried to find documentation on a MaxPriorityQueue object but anything using a MPQ was implemented from scratch.

If someone could shed a bit of light on why this will not run in my personal environment, (nodejs, VSCode), I would appreciate it.

Demmy answered 28/6, 2022 at 18:17 Comment(1)
We can't tell what is available in the leetcode environment or not, but there certainly is no MaxPriorityQueue in native JS.Womanish
M
10

This is because you have @datastructures-js/priority-queue library imported in the JS runtime by default. It is mentioned https://support.leetcode.com/hc/en-us/articles/360011833974-What-are-the-environments-for-the-programming-languages-.

In your own run time, you will have to import it as

const {
  PriorityQueue,
  MinPriorityQueue,
  MaxPriorityQueue,
} = require('@datastructures-js/priority-queue');

or

import {
  PriorityQueue,
  MinPriorityQueue,
  MaxPriorityQueue,
  ICompare,
  IGetCompareValue,
} from '@datastructures-js/priority-queue';
Millipede answered 15/7, 2022 at 1:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.