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 -1 if 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 change and find

Visualization

Tap to expand
Number Container System: Store and Find OperationsContainer System102010index 1index 2index 3Operations:• change(1, 10) → store 10 at index 1• change(2, 20) → store 20 at index 2• change(3, 10) → store 10 at index 3• find(10) → returns 1 (smallest index with 10)• find(20) → returns 2 (only index with 20)• find(30) → returns -1 (not found)Efficient lookup: O(1) change, O(log k) find with heaps
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
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen