Design a Number Container System - Problem
Design a number container system that can perform the following operations:
- Insert or Replace a number at the given index in the system.
- Return the smallest index for the given number in the system.
Implement the NumberContainers class:
NumberContainers()Initializes the number container system.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.int find(int number)Returns the smallest index for the given number, or-1if there is no index that is filled by number in the system.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["NumberContainers", "change", "find", "change", "find", "find"], values = [[], [1, 10], [1], [2, 20], [1], [3]]
›
Output:
[1, 1, -1]
💡 Note:
NumberContainers nc = new NumberContainers(); nc.change(1, 10); // container[1] = 10. nc.find(1) returns 1; nc.change(2, 20); // container[2] = 20. nc.find(1) returns 1; nc.find(3) returns -1 (not found).
Example 2 — Multiple Indices Same Number
$
Input:
operations = ["NumberContainers", "change", "change", "find", "change", "find"], values = [[], [1, 10], [3, 10], [10], [2, 10], [10]]
›
Output:
[1, 1]
💡 Note:
Multiple indices can have same number. System returns smallest index: indices 1 and 3 both have 10, so find(10) returns 1. After adding index 2 with 10, find(10) still returns 1 (smallest).
Example 3 — Replace Existing Value
$
Input:
operations = ["NumberContainers", "change", "find", "change", "find"], values = [[], [1, 10], [10], [1, 20], [10]]
›
Output:
[1, -1]
💡 Note:
Initially container[1] = 10, so find(10) returns 1. Then change(1, 20) replaces the value, so find(10) returns -1 (no longer exists).
Constraints
- 1 ≤ index, number ≤ 109
-
At most 105 calls to
changeandfind
Visualization
Tap to expand
Understanding the Visualization
1
Input
Operations: change(1,10), find(1), change(2,20)
2
Process
Maintain index→number mapping and reverse lookup
3
Output
Find operations return smallest index or -1
Key Takeaway
🎯 Key Insight: Use dual hash maps - one for direct index access, another with min-heaps for efficient minimum index queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code