MediumNo. 1188LeetCode Premium

Design Bounded Blocking Queue — LeetCode 1188 Python Solution

Topics
Concurrency
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

PythonSolution
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

Related problems
No.ProblemDifficulty
1114Print in OrderEasy
1115Print FooBar AlternatelyMedium
1116Print Zero Even OddMedium
1117Building H2OMedium
1184Distance Between Bus StopsEasy
0057Insert IntervalMedium

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.

Free to download. Check it runs on your machine, then pick a plan.