![]() |
VOOZH | about |
Design a SpecialQueue that supports enqueue(x), dequeue(), getFront(), and getMin() in O(1) time.
Input: operations[] = [enqueue(4), enqueue(2), enqueue(1), getMin(), enqueue(6), dequeue(), getFront(), getMin()]
Output: [1, 2, 1]
Explanation:
enqueue(4): Queue = [4]
enqueue(2): Queue = [4, 2]
enqueue(1): Queue = [4, 2, 1]
getMin(): Minimum element is 1
enqueue(6): Queue = [4, 2, 1, 6]
dequeue(): Removes 4 β Queue = [2, 1, 6]
getFront(): Front element is 2
getMin(): Minimum element is 1
The idea is to use an auxiliary Deque to keep track of minimum elements while maintaining normal queue operations. By storing elements in sorted order inside the Deque, we can always retrieve the minimum in O(1) time.
Working of the Approach:
Enqueue(x):
-> Insert x into the main queue (q1).
-> In the deque (q2), remove all elements from the back that are larger than x (since they canβt be the minimum anymore), then insert x at the back.
Dequeue():
-> Remove the front element from the main queue (q1).
-> If this element is equal to the front of the deque (q2), also remove it from the deque to keep both structures in sync.
getMin(): Return the front of the deque (q2.front()), which always stores the current minimum element in the queue.
getFront(): Return the front element of the main queue (q1.front()), i.e., the element that would be removed first if dequeue() is called.
Note: In JavaScript, thereβs no built-in queue, so we implement a custom queue using a doubly linked list for O(1) enqueue and dequeue.
1 2 1