[LeetCode] 2349. Design a Number Container System (Python)

2025. 2. 8. 15:37·알고리즘/LeetCode

 

난이도: Medium

문제 설명


Design a number container system that can do the following:

  • 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.

 

문제 예제


Example 1:

Input
["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"]
[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]
Output
[null, -1, null, null, null, null, 1, null, 2]

Explanation
NumberContainers nc = new NumberContainers();
nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.
nc.change(2, 10); // Your container at index 2 will be filled with number 10.
nc.change(1, 10); // Your container at index 1 will be filled with number 10.
nc.change(3, 10); // Your container at index 3 will be filled with number 10.
nc.change(5, 10); // Your container at index 5 will be filled with number 10.
nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.
nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. 
nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.

 

제한 사항


  • 1 <= index, number <= 109
  • At most 105 calls will be made in total to change and find.

 

✏️ Solution(솔루션)


class NumberContainers:
    def __init__(self):
        self.container = defaultdict(SortedSet)
        self.idx = defaultdict(int)

    def change(self, index: int, number: int) -> None:
        if self.idx[index] != 0:
            self.container[self.idx[index]].remove(index)
            if not self.container[self.idx[index]]:
                del self.container[self.idx[index]]

        self.container[number].add(index)
        self.idx[index] = number

    def find(self, number: int) -> int:
        if not self.container[number]:
            return -1
        return self.container[number][0]

# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)

 

defaultdict(SortedSet)과 defaultdict(int)를 통해 해결했다.

 

change에 인자로 들어온 index가 self.idx에 있다면 self.container[self.idx[index]]에 들어가 있는 index를 지워주었다.

이때 self.container[self.idx[index]]의 리스트가 비었다면 del을 통해 아예 삭제 시켜주었다.

 

그리고 self.container[number].add(index)와 self.idx[index] = number을 통해 새로 업데이트 해주었다.

 

find는 self.container[number]가 빈 리스트이면 -1을 반환했고, 아니면 제일 작은 index인 self.container[number][0]를 반환했다.

 


 

처음에는 다음과 같이 heapq를 통해 진행하였는데 Wrong Answer 판정을 받았다.

import heapq
class NumberContainers:

    def __init__(self):
        self.container = {}
        self.idx = {}

    def change(self, index: int, number: int) -> None:
        if index in self.idx:
            self.container[self.idx[index]].remove(index)
            if not self.container[self.idx[index]]:
                del self.container[self.idx[index]]
        
        if number not in self.container:
            self.container[number] = []

        heapq.heappush(self.container[number], index)
        self.idx[index] = number
        

    def find(self, number: int) -> int:
        if number not in self.container:
            return -1
        x = heapq.heappop(self.container[number])
        heapq.heappush(self.container[number], x)
        return x

# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)

 

이유를 알아보다가 heapq 리스트에서 remove를 사용하면 heapq의 성질이 깨질 수 있다고 한다.

 

그러다가 알게된 것이 SortedSet이다. 이를 이용하면 제일 앞 요소가 제일 작은 값이기 때문에 좀 더 편하게 사용할 수 있었다.


문제: 2349. Design a Number Container System

 

깃허브: github

 

algorithmPractice/LeetCode/2434-design-a-number-container-system at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com

 

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 3174. Clear Digits (Python)  (0) 2025.02.10
[LeetCode] 2364. Count Number of Bad Pairs (Python)  (0) 2025.02.09
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)  (1) 2025.02.07
[LeetCode] 1726. Tuple with Same Product (Python)  (0) 2025.02.06
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python)  (0) 2025.02.05
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 3174. Clear Digits (Python)
  • [LeetCode] 2364. Count Number of Bad Pairs (Python)
  • [LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)
  • [LeetCode] 1726. Tuple with Same Product (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    알고리즘
    아파치 스파크
    문자열
    쿠버네티스
    Apache Spark
    아파치 하둡
    분산처리
    dfs
    heapq
    프로그래머스
    도커
    누적합
    파이썬
    백트래킹
    DP
    우선순위큐
    리트코드
    티스토리챌린지
    이진탐색
    그래프
    Python
    leetcode
    Kubernetes
    코딩테스트
    BFS
    docker
    오블완
    분산
    String
    programmers
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2349. Design a Number Container System (Python)
상단으로

티스토리툴바