LeetCode 2349: Design a Number Container System Solution

Master LeetCode problem 2349 (Design a Number Container System), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2349. Design a Number Container System

Problem Explanation

Explanation

To implement the number container system, we can use a hashmap to store the numbers and their corresponding indices. We will also maintain a separate hashmap to store the indices that are filled in the system.

Algorithm:

  1. Initialize two hashmaps: one to store number to index mappings and another one to store index to number mappings.
  2. Implement the change method to update the number at a given index.
  3. Implement the find method to return the smallest index for a given number.

Time Complexity:

  • For each change operation: O(1) on average
  • For each find operation: O(n) in the worst case (where n is the total number of indices) Overall time complexity: O(n) where n is the total number of indices filled.

Space Complexity:

  • O(n) where n is the total number of indices filled.

Solution Code

import java.util.HashMap;

class NumberContainers {
    HashMap<Integer, Integer> numToIndex;
    HashMap<Integer, Integer> indexToNum;

    public NumberContainers() {
        numToIndex = new HashMap<>();
        indexToNum = new HashMap<>();
    }

    public void change(int index, int number) {
        if (indexToNum.containsKey(index)) {
            int prevNum = indexToNum.get(index);
            numToIndex.remove(prevNum);
        }
        numToIndex.put(number, index);
        indexToNum.put(index, number);
    }

    public int find(int number) {
        if (numToIndex.containsKey(number)) {
            return numToIndex.get(number);
        }
        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2349 (Design a Number Container System)?

This page provides optimized solutions for LeetCode problem 2349 (Design a Number Container System) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2349 (Design a Number Container System)?

The time complexity for LeetCode 2349 (Design a Number Container System) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2349 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2349 in Java, C++, or Python.

Back to LeetCode Solutions