VOOZH about

URL: https://www.geeksforgeeks.org/dsa/design-a-queue-data-structure-to-get-minimum-or-maximum-in-o1-time/

⇱ Queue with Minimum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queue with Minimum

Last Updated : 20 Sep, 2025

Design a SpecialQueue that supports enqueue(x), dequeue(), getFront(), and getMin() in O(1) time.

  • enqueue(x) β†’ insert element x at the rear of the queue
  • dequeue() β†’ remove the element from the front of the queue
  • getFront() β†’ return the front element without removing; -1 if empty
  • getMin() β†’ return the minimum element in the queue; -1 if empty

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

[Approach] Using Dequeue - O(1) Time and O(n) Space

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.


Output
1 2 1 
Comment
Article Tags:
Article Tags: