Skip to content

Commit 98e96c0

Browse files
authored
Create Smallest Number in Infinite Set.py
1 parent f4ed5c1 commit 98e96c0

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Smallest Number in Infinite Set.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# https://leetcode.com/problems/smallest-number-in-infinite-set/
2+
3+
import heapq
4+
5+
class SmallestInfiniteSet:
6+
7+
def __init__(self):
8+
9+
# Create a heap and a set
10+
self.heap = list()
11+
self.set = set()
12+
13+
# Create a variable to hold the smallest number
14+
self.smallestNum = 1
15+
16+
def popSmallest(self) -> int:
17+
18+
# OBJECTIVE: Return smallest element from heap and set
19+
20+
# Check if heap isn't empty
21+
if self.heap:
22+
23+
# Pop element from heap and set
24+
popped = heapq.heappop(self.heap)
25+
self.set.remove(popped)
26+
27+
# Return popped element
28+
return popped
29+
30+
# If heap is empty, return smallest number based on variable
31+
# NOTE: smallestNum needs to be updated before returned
32+
self.smallestNum += 1
33+
return self.smallestNum - 1
34+
35+
def addBack(self, num: int) -> None:
36+
37+
# If num is smaller than smallest and it doesn't exist in set, add it to set and heap
38+
if num < self.smallestNum and num not in self.set:
39+
self.set.add(num)
40+
heapq.heappush(self.heap, num)
41+
42+
# Your SmallestInfiniteSet object will be instantiated and called as such:
43+
# obj = SmallestInfiniteSet()
44+
# param_1 = obj.popSmallest()
45+
# obj.addBack(num)

0 commit comments

Comments
 (0)