Input:
push_rear(1)push_rear(3)push_rear(0)get_min()pop_front()get_min()Output:
01Explanation:
After pushing 1,3, and 0, the queue is[1,3,0]. The minimum is0.After popping the front element(1), the queue is[3,0]. The minimum is now 0.
You can implement a stack with O(1) operations for pop(), push(), and get_min() by storing the current minimum with each element. For instance, the stack [4, 2, 5, 1] (1 is the top) would be represented as [(4, 4), (2, 2), (5, 2), (1, 1)]. Refer to the Min Stack Problem for more details.
To construct a queue using two stacks, push elements into one stack and pop them from another. If the second stack is empty during a pop operation, move all elements from the first stack to the second. The minimum element of the queue can be found by comparing the smallest elements from each of the two min-stacks. This method ensures O(1) time complexity for get_min() and push(), and amortized O(1) time complexity for pop().
You can implement a stack with O(1) pop(), push() and get_min(): just store the current minimum together with each element. So, for example, the stack [4, 2, 5, 1] (1 on top) becomes [(4, 4), (2, 2), (5, 2), (1, 1)].
Method 1 can be time-consuming in an interview setting. Instead, consider using three queues. The first queue handles enqueue and dequeue operations in O(1) time. The other two queues track the minimum element, and we adjust these queues during push and pop operations to maintain the minimum element in O(1) time.
To ensure that all operations - push_rear(), pop_front(), and get_min(), are performed in constant time, we will use two main data structures: a deque (double-ended queue) to store the actual elements of the queue and a secondary deque to keep track of the minimum values. The second deque helps in keeping track of the minimum value in constant time even as elements are added or removed from the queue.
Here is the approach:
push_rear(element): Add the element to the rear of the main deque. In the secondary deque, remove elements from the rear that are greater than the new element before adding the new element.
pop_front(): Remove the element from the front of both deques.
get_min(): Retrieve the front element of the secondary deque, which holds the minimum value of the queue.
⏰ Time complexity: O(1) for all operations (push_rear(), pop_front(), and get_min())
🧺 Space complexity: O(n), where n is the number of elements in the queue since each element will occupy space in both the main deque and potentially the secondary deque.