
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Design a queue data structure to get minimum or maximum in O(1) time
In data structure & algorithm, we have a deque header file that handles the properties of stack and queue. For getting minimum and maximum value from O(1) time complexity, we need constant time. So, deque is one of the possible advantages of using both stack and queue.
O(1) Time Complexity
The O(1) time complexity is also known as constant time which defines an algorithm for taking the same amount of time instead of using size input.
Syntax
The basic syntax of deque data structure is as follows:
deque <data_type> name_of_queue;
Here,
- deque : It is stand for double-ended queue that ordered a group of items or numbers equivalent to the queue.
- data_type : The type of data used like int, float, etc.
- name_of_queue : Any name given to the queue like ab, cd, etc.
Getting Minimum and Maximum in O(1) using Deque
To get the maximum and minimum number in O(1), use the concept of deque that store the element in increasing order for minimum retrieval and decreasing order for maximum retrieval.
For better understanding,
- If we want to return the minimum element then store the element in the form of increasing order. Here, the front holds the smallest element.
- Secondly, if we want to return the maximum element then store the element in the form of decreasing order. Here, the front will hold the largest element.
Syntax
Following are the built-in functions of C++ STL to solve the problem in O(1) time complexity:
// insertion of elements push_back(name_of_iterator or values)
Example
In this example, we use the built-in functions from the headers like <climits> and <deque> that allow us to set the minimum and maximum value in O(1) time and then loop to start iterating for the insertion of elements using pushback(iterator).
#include<iostream> #include<climits> #include<deque> using namespace std; int main() { deque<int> dq; int min_element = INT_MAX; int max_element = INT_MIN; // Insert elements and track min/max in O(1) for (int i = 10; i <= 15; i++) { dq.push_back(i); if (i < min_element) min_element = i; if (i > max_element) max_element = i; } // Print the minimum and maximum elements cout << "Minimum element: " << min_element << endl; cout << "Maximum element: " << max_element << endl; return 0; }
The above code produces the following output:
Minimum element: 10 Maximum element: 15
Deque method:
Time complexity: O(1) Auxiliary Space: O(1)