LeetCode 1188: Design Bounded Blocking Queue Solution
Master LeetCode problem 1188 (Design Bounded Blocking Queue), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1188. Design Bounded Blocking Queue
Problem Explanation
Explanation:
To design a bounded blocking queue, we can use a combination of a synchronized queue to store the elements and two semaphores to control the access to the queue. One semaphore will handle the empty slots in the queue, and the other semaphore will handle the occupied slots in the queue.
- We will use a synchronized queue to store the elements. This queue will handle all the blocking and unblocking operations required for the bounded queue.
- We will use two semaphores, one to control the number of empty slots in the queue (
emptySlots) and the other to control the number of occupied slots in the queue (occupiedSlots). - When inserting an element into the queue, we need to acquire a permit from the
emptySlotssemaphore and then add the element to the queue. After adding the element, we release a permit to theoccupiedSlotssemaphore. - When removing an element from the queue, we need to acquire a permit from the
occupiedSlotssemaphore and then remove the element from the queue. After removing the element, we release a permit to theemptySlotssemaphore. :
Solution Code
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
class BoundedBlockingQueue {
private ArrayBlockingQueue<Integer> queue;
private Semaphore emptySlots, occupiedSlots;
public BoundedBlockingQueue(int capacity) {
queue = new ArrayBlockingQueue<>(capacity);
emptySlots = new Semaphore(capacity);
occupiedSlots = new Semaphore(0);
}
public void enqueue(int element) throws InterruptedException {
emptySlots.acquire();
queue.add(element);
occupiedSlots.release();
}
public int dequeue() throws InterruptedException {
occupiedSlots.acquire();
int element = queue.poll();
emptySlots.release();
return element;
}
public int size() {
return queue.size();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1188 (Design Bounded Blocking Queue)?
This page provides optimized solutions for LeetCode problem 1188 (Design Bounded Blocking Queue) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1188 (Design Bounded Blocking Queue)?
The time complexity for LeetCode 1188 (Design Bounded Blocking Queue) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1188 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1188 in Java, C++, or Python.