Design Bounded Blocking Queue — LeetCode 1188 Python Solution

MediumLeetCode PremiumConcurrency
Problem
#1188
Reading time
5 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview