MediumNo. 1188LeetCode Premium
Design Bounded Blocking Queue — LeetCode 1188 Python Solution
- Topics
- Concurrency
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Implement a thread-safe bounded blocking queue that has the following methods: BoundedBlockingQueue(int capacity) The constructor initializes the queue with a maximum capacity. void enqueue(int element) Adds an element to the front of the queue.
Example
- Input
- 1
- Output
- [1,0,2,2]
- Explanation
- Number of producer threads = 1
Python solution
from threading import Semaphore
class BoundedBlockingQueue(object):
def __init__(self, capacity: int):
self.s1 = Semaphore(capacity)
self.s2 = Semaphore(0)
self.q = deque()
def enqueue(self, element: int) -> None:
self.s1.acquire()
self.q.append(element)
self.s2.release()
def dequeue(self) -> int:
self.s2.acquire()
ans = self.q.popleft()
self.s1.release()
return ans
def size(self) -> int:
return len(self.q)Complexity
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1114 | Print in Order | Easy |
| 1115 | Print FooBar Alternately | Medium |
| 1116 | Print Zero Even Odd | Medium |
| 1117 | Building H2O | Medium |
| 1184 | Distance Between Bus Stops | Easy |
| 0057 | Insert Interval | Medium |
Frequently asked questions
- How hard is LeetCode 1188. Design Bounded Blocking Queue?
LeetCode 1188. Design Bounded Blocking Queue is rated Medium on LeetCode.
- What topics does LeetCode 1188. Design Bounded Blocking Queue cover?
LeetCode 1188. Design Bounded Blocking Queue is tagged Concurrency on LeetCode.
- Is LeetCode 1188. Design Bounded Blocking Queue a premium problem?
Yes. LeetCode 1188. Design Bounded Blocking Queue is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.