✅ Javascript || Priority Queue || Detailed Explanation || Clean Code
Let\'s walk through question description\n\nDesign a number container system that can do the following:\n\n- Insert or Replace a number at the given index in th
Let\'s walk through question description\n\nDesign a number container system that can do the following:\n\n- Insert or Replace a number at the given index in the system.\n*and* `void change(int index, int number)` Fills the container at index with the number. If there is already a number at that index, replace it.\n**=>** We need to store `index` and `number at this index`. We can use **array** to store it. However, it would be a **waste of memory** if we use **array** here as `number` filled at random `index` in **array**. I decided to use **HashMap** here to **keep track** of number at index. (`{ index: numberAtIndex }`). Every time we called `change` function, we will set a `number` to the `index`\n\n- Return the smallest index for the given number in the system.\n**=>** Why we have **smallest index** here ? It is because of we can fill a `number` to many `index`. So it could be like mapping `num1` to many indexes `[i1, i2, i3 ....]`. `find` function will return **smallest i** in `[i1, i2, i3 ....]`. Thinking about using **Priority Queue** is a good start. **Priority Queue** is efficient finding **smallest** or largest.\nEvery time we called `change` function, we will **enqueue** an `index` to the `number`\n\n\n\u2757\uFE0F\u2757\uFE0F\u2757\uFE0FThere is an issue with above walk through. We can **replace** a number at a specific index. `find` function will return wrong index if we don\'t update the **Priority Queue**. \nIf `front_number` at **front** element of the **queue** (`index`) is not the `number` we need to `find`, then the `front_number` is replaced by another `number` before. We are no longer need `front_number`. It is safe to **dequeue** it from the queue.\n\n<br />\n\u2139\uFE0F [MinPriorityQueue](https://support.leetcode.com/hc/en-us/articles/360011833974-What-are-the-environments-for-the-programming-languages-) usage can be found here at Javascript row\n\n<br />\n\n\u2139\uFE0F [My javascript solution collection](https://github.com/toantd90/leetcode-js-solutions)\n\n<br />\n\n\n\n\n```\nclass NumberContainers {\n  constructor() {\n    this.nums = {};\n    this.numMap = {};\n  }\n\n  change(index, number) {\n    this.nums[index] = number;\n\n    if (!this.numMap[number]) {\n      this.numMap[number] = new MinPriorityQueue();\n    }\n\n    this.numMap[number].enqueue(index);\n  }\n\n  find(number) {\n    while (\n      this.numMap[number] &&\n      this.numMap[number].size() > 0 &&\n      this.nums[this.numMap[number].front().element] !== number\n    ) {\n      this.numMap[number].dequeue();\n    }\n\n    return this.numMap[number] && this.numMap[number].size() > 0\n      ? this.numMap[number].front().element\n      : -1;\n  }\n}\n\n```
['Hash Table', 'Heap (Priority Queue)', 'JavaScript']