#2349

Design a Number Container System

Medium
Hash TableDesignHeap (Priority Queue)Ordered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(n)
💡

Intuition

Time O(log n)Space O(n)

In the optimal solution, we use two hash maps: one to map indices to numbers and another to map numbers to a sorted set of indices. This allows us to efficiently update and retrieve the smallest index for any number.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two hash maps: one for index-to-number and another for number-to-index set.
  2. 2Step 2: For 'change', update the index-to-number map and also update the number-to-index set accordingly.
  3. 3Step 3: For 'find', directly retrieve the smallest index from the number-to-index set.
solution.py20 lines
1from sortedcontainers import SortedSet
2
3class NumberContainers:
4    def __init__(self):
5        self.index_to_number = {}
6        self.number_to_indices = {}
7
8    def change(self, index: int, number: int) -> None:
9        if index in self.index_to_number:
10            old_number = self.index_to_number[index]
11            self.number_to_indices[old_number].remove(index)
12            if not self.number_to_indices[old_number]:
13                del self.number_to_indices[old_number]
14        self.index_to_number[index] = number
15        if number not in self.number_to_indices:
16            self.number_to_indices[number] = SortedSet()
17        self.number_to_indices[number].add(index)
18
19    def find(self, number: int) -> int:
20        return self.number_to_indices[number][0] if number in self.number_to_indices else -1

Complexity note: The time complexity is O(log n) for both 'change' and 'find' operations due to the use of a sorted set (or tree set), which allows for efficient insertions, deletions, and retrievals of the smallest index.

  • 1Using a hash map allows for efficient lookups and updates.
  • 2Maintaining a sorted set for indices enables quick retrieval of the smallest index.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.