🚀 Number Containers System - LeetCode Solution || 💡easy solution || ✅ high efficiency  
IntroductionThe problem requires us to design a Number Containers System that supports two main operations:
Insert or replace a number at a given index.
Find th
# Introduction
The problem requires us to design a **Number Containers System** that supports two main operations:
1. **Insert or replace** a number at a given index.
2. **Find** the smallest index associated with a given number.

To solve this efficiently, we need a data structure that can:
- Store the mapping between indices and their corresponding numbers.
- Maintain a sorted order of indices for each number to quickly retrieve the smallest one.

---

# Step-by-Step Approach ✨
To achieve efficient insertions, replacements, and retrievals, we use:
- A **hash map (`unordered_map`)** to store number-to-index mappings.
- A **min-heap (`priority_queue`)** to keep track of indices sorted in ascending order for each number.

### **Data Structures Used**
- `unordered_map<long, priority_queue<long, vector<long>, greater<long>>> mp;`  
  → Stores numbers as keys, mapping to a min-heap of indices.
- `unordered_map<long, long> ind;`  
  → Stores indices as keys, mapping to their corresponding numbers.

### **Operations**
#### **1. `change(int index, int number)`**
- Updates the `ind` map to reflect the new number at the given index.
- Pushes the index into the corresponding min-heap in `mp`.

#### **2. `find(int number)`**
- Retrieves the smallest index associated with the given number.
- Uses a while loop to remove outdated indices from the heap until the top of the heap reflects the correct mapping.
- Returns the smallest valid index or `-1` if none exists.

---

# Complexity Analysis ⏳
- **Time Complexity:**
  - `change()`: $$O(log N)$$ due to insertion into the heap.
  - `find()`: $$O(log N)$$ in the worst case (cleaning outdated indices from the heap).
- **Space Complexity:** $$O(N)$$ for storing mappings in `unordered_map` and heaps.

---
![c1ee5054-dd07-4caa-a7df-e21647cfae9e_1709942227.5165014.png](https://assets.leetcode.com/users/images/f7b9f2fe-a37f-4eaf-8e02-5eb351b33faa_1738997700.9441066.png)

# Code 💻
```cpp []
class NumberContainers {
public:
    unordered_map<long, priority_queue<long, vector<long>, greater<long>>> mp;  // number -> min-heap of indices
    unordered_map<long, long> ind; // index -> number

    NumberContainers() {}
    
    void change(int index, int number) {
        ind[index] = number;  // Update index-to-number mapping
        mp[number].push(index); // Push index to min-heap
    }
    
    int find(int number) {
        while (!mp[number].empty()) {
            int minIndex = mp[number].top();  // Get smallest index
            if (ind[minIndex] == number) {
                return minIndex; // Return if still valid
            }
            mp[number].pop(); // Remove outdated entry
        }
        return -1; // No valid index found
    }
};
```


```python []
class NumberContainers:
    def __init__(self):
        self.mp = {}  # Number -> min-heap of indices
        self.ind = {}  # Index -> Number

    def change(self, index: int, number: int) -> None:
        self.ind[index] = number  # Update mapping
        if number not in self.mp:
            self.mp[number] = []
        heapq.heappush(self.mp[number], index)  # Push index to min-heap

    def find(self, number: int) -> int:
        if number not in self.mp:
            return -1
        while self.mp[number]:
            min_index = self.mp[number][0]  # Get smallest index
            if self.ind.get(min_index) == number:
                return min_index
            heapq.heappop(self.mp[number])  # Remove outdated entry
        return -1
```

---

# Example Walkthrough 📌
### **Input & Execution**
```cpp
NumberContainers nc;
nc.find(10);      // -1 (No index has 10 yet)
nc.change(2, 10);
nc.change(1, 10);
nc.change(3, 10);
nc.change(5, 10);
nc.find(10);      // 1 (Smallest index with 10)
nc.change(1, 20);
nc.find(10);      // 2 (Index 1 no longer has 10)
```

### **Output**
```
[null, -1, null, null, null, null, 1, null, 2]
```

---

## Final Thoughts 🎯
This approach efficiently maintains and retrieves indices for numbers while keeping operations optimal using **hash maps and heaps**.

💡 **Key Takeaways:**
- `unordered_map` provides fast lookups.
- `priority_queue` (min-heap) ensures retrieval of the smallest index efficiently.
- Efficient handling of outdated indices prevents incorrect results.

Thank you for your time! I hope this guide was helpful. If you found this useful,**Upvote**, feel free to share or ask questions! 😊🚀

$$ $$
![1HBC0324_COV.jpg](https://assets.leetcode.com/users/images/d528550a-106f-49ad-b5b4-44ad5a582580_1738997638.7759693.jpeg)


['Hash Table', 'Design', 'Heap (Priority Queue)', 'Python', 'C++']