Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack. Thereafter, the stack modifies to {10}.Push(4): 4 is added to the top of the stack. Thereafter, the stack modifies to {10, 4}.Push(9): 9 is added to the top of the stack. Thereafter, the stack modifies to {10, 4, 9}.Push(6): 6 is added to the top of the stack. Thereafter, the stack modifies to {10, 4, 9, 6}.Push(5): 5 is added to the top of the stack. Thereafter, the stack modifies to {10, 4, 9, 6, 5}.Peek(): Prints the top element of the stack 5.getMin(): Prints the minimum element of the stack 4.Pop(): Deletes the top most element, 5 from the stack. Thereafter, the stack modifies to {10, 4, 9, 6}.Pop(): Deletes the top most element, 6 from the stack. Thereafter, the stack modifies to {10, 4, 9}.Pop(): Deletes the top most element, 9 from the stack. Thereafter, the stack modifies to {10, 4}.Pop(): Deletes the top most element, 4 from the stack. Thereafter, the stack modifies to {10}.Peek(): Prints the top element of the stack 10.getMin(): Prints the minimum element of the stack 10. Approach: To implement a dynamic stack using an array the idea is to double the size of the array every time the array gets full. Follow the steps below to solve the problem: Initialize an array, say arr[] with an initial size 5, to implement the stack.Also, initialize two variables, say top and minEle to store the index of the top element of the stack and minimum element of the stack.Now, perform the following stack operations: isEmpty(): Checks if the stack is empty or not.Return true if the top is less or equal to 0. Otherwise, return false.Push(x): Inserts x at the top of the stack.If the stack is empty, insert x into the stack and make minEle equal to x.If the stack is not empty, compare x with minEle. Two cases arise:If x is greater than or equal to minEle, simply insert x.If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x.If the array used is full then, double the size of the array and then copy all the elements of the previous array to the new array and then assign the address of the new array to the original array. Thereafter, perform the push operation as discussed above.Pop(): Removes an element from the top of the stack.Let the removed element be y. Two cases ariseIf y is greater than or equal to minEle, the minimum element in the stack is still minEle.If y is less than minEle, the minimum element now becomes (2*minEle – y), so update minEle as minEle = 2*minEle-y.getMin(): Finds the minimum value of the stack.If the stack is not empty then return the value of minEle. Otherwise, return "-1" and print "Underflow". Illustration: Push(x) Number to be Inserted: 3, Stack is empty, so insert 3 into stack and minEle = 3.Number to be Inserted: 5, Stack is not empty, 5> minEle, insert 5 into stack and minEle = 3.Number to be Inserted: 2, Stack is not empty, 2< minEle, insert (2*2-3 = 1) into stack and minEle = 2.Number to be Inserted: 1, Stack is not empty, 1< minEle, insert (2*1-2 = 0) into stack and minEle = 1.Number to be Inserted: 1, Stack is not empty, 1 = minEle, insert 1 into stack and minEle = 1.Number to be Inserted: -1, Stack is not empty, -1 < minEle, insert (2*-1 – 1 = -3) into stack and minEle = -1.Pop() Initially the minimum element minEle in the stack is -1.Number removed: -3, Since -3 is less than the minimum element the original number being removed is minEle which is -1, and the new minEle = 2*-1 – (-3) = 1Number removed: 1, 1 == minEle, so number removed is 1 and minEle is still equal to 1.Number removed: 0, 0< minEle, original number is minEle which is 1 and new minEle = 2*1 – 0 = 2.Number removed: 1, 1< minEle, original number is minEle which is 2 and new minEle = 2*2 – 1 = 3.Number removed: 5, 5> minEle, original number is 5 and minEle is still 3 Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // A class to create // our special stack class Stack { private: // Initial size of // the Array int Max = 5; // Array for the stack // implementation int* arr = new int(Max); // Stores the minimum // Element of the stack int minEle = 0; // Stores the top element // of the stack int top = 0; public: // Method to check whether // stack is empty or not bool empty() { if (top <= 0) { return true; } else { return false; } } // Method to push elements // to the Special Stack void push(int x) { // If stack is empty if (empty()) { // Assign x to minEle minEle = x; // Assign x to arr[top] arr[top] = x; // Increment top by 1 top++; } // If array is full else if (top == Max) { // Update the Max size Max = 2 * Max; int* temp = new int(Max); // Traverse the array arr[] for (int i = 0; i < top; i++) { temp[i] = arr[i]; } // If x is less than minEle if (x < minEle) { // Push 2*x-minEle temp[top] = 2 * x - minEle; // Assign x to minEle minEle = x; top++; } // Else else { // Push x to stack temp[top] = x; top++; } // Assign address of the // temp to arr arr = temp; } else { // If x is less // than minEle if (x < minEle) { // Push 2*x-minEle arr[top] = 2 * x - minEle; top++; // Update minEle minEle = x; } else { // Push x to the // stack arr[top] = x; top++; } } } // Method to pop the elements // from the stack. void pop() { // If stack is empty if (empty()) { cout << "Underflow" << endl; return; } // Stores the top element // of the stack int t = arr[top - 1]; // If t is less than // the minEle if (t < minEle) { // Pop the minEle cout << "Popped element : " << minEle << endl; // Update minEle minEle = 2 * minEle - t; } // Else else { // Pop the topmost element cout << "Popped element : " << t << endl; } top--; return; } // Method to find the topmost // element of the stack int peek() { // If stack is empty if (empty()) { cout << "Underflow" << endl; return -1; } // Stores the top element // of the stack int t = arr[top - 1]; // If t is less than // the minEle if (t < minEle) { return minEle; } // Else else { return t; } } // Method to find the Minimum // element of the Special stack int getMin() { // If stack is empty if (empty()) { cout << "Underflow" << endl; return -1; } // Else else { return minEle; } } }; // Driver Code int main() { Stack S; S.push(10); S.push(4); S.push(9); S.push(6); S.push(5); cout << "Top Element : " << S.peek() << endl; cout << "Minimum Element : " << S.getMin() << endl; S.pop(); S.pop(); S.pop(); S.pop(); cout << "Top Element : " << S.peek() << endl; cout << "Minimum Element : " << S.getMin() << endl; return 0; } Java // Java program for the above approach public class Main { // Initial size of // the Array static int Max = 5; // Array for the stack // implementation static int[] arr = new int[Max]; // Stores the minimum // Element of the stack static int minEle = 0; // Stores the top element // of the stack static int Top = 0; // Method to check whether // stack is empty or not static boolean empty() { if (Top <= 0) { return true; } else { return false; } } // Method to push elements // to the Special Stack static void push(int x) { // If stack is empty if (empty()) { // Assign x to minEle minEle = x; // Assign x to arr[top] arr[Top] = x; // Increment top by 1 Top++; } // If array is full else if (Top == Max) { // Update the Max size Max = 2 * Max; int[] temp = new int[Max]; // Traverse the array arr[] for (int i = 0; i < Top; i++) { temp[i] = arr[i]; } // If x is less than minEle if (x < minEle) { // Push 2*x-minEle temp[Top] = 2 * x - minEle; // Assign x to minEle minEle = x; Top++; } // Else else { // Push x to stack temp[Top] = x; Top++; } // Assign address of the // temp to arr arr = temp; } else { // If x is less // than minEle if (x < minEle) { // Push 2*x-minEle arr[Top] = 2 * x - minEle; Top++; // Update minEle minEle = x; } else { // Push x to the // stack arr[Top] = x; Top++; } } } // Method to pop the elements // from the stack. static void pop() { // If stack is empty if (empty()) { System.out.print("Underflow"); return; } // Stores the top element // of the stack int t = arr[Top - 1]; // If t is less than // the minEle if (t < minEle) { // Pop the minEle System.out.println("Popped element : " + minEle); // Update minEle minEle = 2 * minEle - t; } // Else else { // Pop the topmost element System.out.println("Popped element : " + t); } Top--; return; } // Method to find the topmost // element of the stack static int peek() { // If stack is empty if (empty()) { System.out.println("Underflow"); return -1; } // Stores the top element // of the stack int t = arr[Top - 1]; // If t is less than // the minEle if (t < minEle) { return minEle; } // Else else { return t; } } // Method to find the Minimum // element of the Special stack static int getMin() { // If stack is empty if (empty()) { System.out.println("Underflow"); return -1; } // Else else { return minEle; } } // Driver code public static void main(String[] args) { push(10); push(4); push(9); push(6); push(5); System.out.println("Top Element : " + peek()); System.out.println("Minimum Element : " + getMin()); pop(); pop(); pop(); pop(); System.out.println("Top Element : " + peek()); System.out.println("Minimum Element : " + getMin()); } } // This code is contributed by rameshtravel07. Python3 # Python3 program for the above approach # Initial size of # the Array Max = 5 # Array for the stack # implementation arr = [0]*Max # Stores the minimum # Element of the stack minEle = 0 # Stores the top element # of the stack Top = 0 # Method to check whether # stack is empty or not def empty(): if (Top <= 0): return True else: return False # Method to push elements # to the Special Stack def push(x): global arr, Top, Max, minEle # If stack is empty if empty(): # Assign x to minEle minEle = x # Assign x to arr[top] arr[Top] = x # Increment top by 1 Top+=1 # If array is full elif (Top == Max): # Update the Max size Max = 2 * Max temp = [0]*Max # Traverse the array arr[] for i in range(Top): temp[i] = arr[i] # If x is less than minEle if (x < minEle): # Push 2*x-minEle temp[Top] = 2 * x - minEle # Assign x to minEle minEle = x Top+=1 # Else else: # Push x to stack temp[Top] = x Top+=1 # Assign address of the # temp to arr arr = temp else: # If x is less # than minEle if (x < minEle): # Push 2*x-minEle arr[Top] = 2 * x - minEle Top+=1 # Update minEle minEle = x else: # Push x to the # stack arr[Top] = x Top+=1 # Method to pop the elements # from the stack. def pop(): global Top, minEle # If stack is empty if empty(): print("Underflow") return # Stores the top element # of the stack t = arr[Top - 1] # If t is less than # the minEle if (t < minEle) : # Pop the minEle print("Popped element :", minEle) # Update minEle minEle = 2 * minEle - t # Else else: # Pop the topmost element print("Popped element :", t) Top-=1 return # Method to find the topmost # element of the stack def peek(): # If stack is empty if empty(): print("Underflow") return -1 # Stores the top element # of the stack t = arr[Top - 1] # If t is less than # the minEle if (t < minEle): return minEle # Else else: return t # Method to find the Minimum # element of the Special stack def getMin(): # If stack is empty if empty(): print("Underflow") return -1 # Else else: return minEle push(10) push(4) push(9) push(6) push(5) print("Top Element :", peek()) print("Minimum Element :", getMin()) pop() pop() pop() pop() print("Top Element :", peek()) print("Minimum Element :", getMin()) # This code is contributed by mukesh07. C# // C# program for the above approach using System; class GFG { // Initial size of // the Array static int Max = 5; // Array for the stack // implementation static int[] arr = new int[Max]; // Stores the minimum // Element of the stack static int minEle = 0; // Stores the top element // of the stack static int Top = 0; // Method to check whether // stack is empty or not static bool empty() { if (Top <= 0) { return true; } else { return false; } } // Method to push elements // to the Special Stack static void push(int x) { // If stack is empty if (empty()) { // Assign x to minEle minEle = x; // Assign x to arr[top] arr[Top] = x; // Increment top by 1 Top++; } // If array is full else if (Top == Max) { // Update the Max size Max = 2 * Max; int[] temp = new int[Max]; // Traverse the array arr[] for (int i = 0; i < Top; i++) { temp[i] = arr[i]; } // If x is less than minEle if (x < minEle) { // Push 2*x-minEle temp[Top] = 2 * x - minEle; // Assign x to minEle minEle = x; Top++; } // Else else { // Push x to stack temp[Top] = x; Top++; } // Assign address of the // temp to arr arr = temp; } else { // If x is less // than minEle if (x < minEle) { // Push 2*x-minEle arr[Top] = 2 * x - minEle; Top++; // Update minEle minEle = x; } else { // Push x to the // stack arr[Top] = x; Top++; } } } // Method to pop the elements // from the stack. static void pop() { // If stack is empty if (empty()) { Console.WriteLine("Underflow"); return; } // Stores the top element // of the stack int t = arr[Top - 1]; // If t is less than // the minEle if (t < minEle) { // Pop the minEle Console.WriteLine("Popped element : " + minEle); // Update minEle minEle = 2 * minEle - t; } // Else else { // Pop the topmost element Console.WriteLine("Popped element : " + t); } Top--; return; } // Method to find the topmost // element of the stack static int peek() { // If stack is empty if (empty()) { Console.WriteLine("Underflow"); return -1; } // Stores the top element // of the stack int t = arr[Top - 1]; // If t is less than // the minEle if (t < minEle) { return minEle; } // Else else { return t; } } // Method to find the Minimum // element of the Special stack static int getMin() { // If stack is empty if (empty()) { Console.WriteLine("Underflow"); return -1; } // Else else { return minEle; } } static void Main() { push(10); push(4); push(9); push(6); push(5); Console.WriteLine("Top Element : " + peek()); Console.WriteLine("Minimum Element : " + getMin()); pop(); pop(); pop(); pop(); Console.WriteLine("Top Element : " + peek()); Console.WriteLine("Minimum Element : " + getMin()); } } // This code is contributed by suresh07. JavaScript <script> // Javascript program for the above approach // Initial size of // the Array let Max = 5; // Array for the stack // implementation let arr = new Array(Max); // Stores the minimum // Element of the stack let minEle = 0; // Stores the top element // of the stack let Top = 0; // Method to check whether // stack is empty or not function empty() { if (Top <= 0) { return true; } else { return false; } } // Method to push elements // to the Special Stack function push(x) { // If stack is empty if (empty()) { // Assign x to minEle minEle = x; // Assign x to arr[top] arr[Top] = x; // Increment top by 1 Top++; } // If array is full else if (Top == Max) { // Update the Max size Max = 2 * Max; let temp = new Array(Max); // Traverse the array arr[] for (let i = 0; i < Top; i++) { temp[i] = arr[i]; } // If x is less than minEle if (x < minEle) { // Push 2*x-minEle temp[Top] = 2 * x - minEle; // Assign x to minEle minEle = x; Top++; } // Else else { // Push x to stack temp[Top] = x; Top++; } // Assign address of the // temp to arr arr = temp; } else { // If x is less // than minEle if (x < minEle) { // Push 2*x-minEle arr[Top] = 2 * x - minEle; Top++; // Update minEle minEle = x; } else { // Push x to the // stack arr[Top] = x; Top++; } } } // Method to pop the elements // from the stack. function pop() { // If stack is empty if (empty()) { document.write("Underflow" + "</br>"); return; } // Stores the top element // of the stack let t = arr[Top - 1]; // If t is less than // the minEle if (t < minEle) { // Pop the minEle document.write("Popped element : " + minEle + "</br>"); // Update minEle minEle = 2 * minEle - t; } // Else else { // Pop the topmost element document.write("Popped element : " + t + "</br>"); } Top--; return; } // Method to find the topmost // element of the stack function peek() { // If stack is empty if (empty()) { document.write("Underflow" + "</br>"); return -1; } // Stores the top element // of the stack let t = arr[Top - 1]; // If t is less than // the minEle if (t < minEle) { return minEle; } // Else else { return t; } } // Method to find the Minimum // element of the Special stack function getMin() { // If stack is empty if (empty()) { document.write("Underflow" + "</br>"); return -1; } // Else else { return minEle; } } push(10); push(4); push(9); push(6); push(5); document.write("Top Element : " + peek() + "</br>"); document.write("Minimum Element : " + getMin() + "</br>"); pop(); pop(); pop(); pop(); document.write("Top Element : " + peek() + "</br>"); document.write("Minimum Element : " + getMin() + "</br>"); // This code is contributed by divyesh072019. </script> OutputTop Element : 5 Minimum Element : 4 Popped element : 5 Popped element : 6 Popped element : 9 Popped element : 4 Top Element : 10 Minimum Element : 10 Time Complexity: O(1) for each operationAuxiliary Space: O(1) Comment More infoAdvertise with us Next Article Asymptotic Notations for Analysis of Algorithms P prathamjha5683 Follow Improve Article Tags : DSA interview-preparation cpp-stack cpp-stack-functions System-Design +1 More Similar Reads Basics & PrerequisitesTime and Space ComplexityMany times there are more than one ways to solve a problem with different algorithms and we need a way to compare multiple ways. Also, there are situations where we would like to know how much time and resources an algorithm might take when implemented. To measure performance of algorithms, we typic 13 min read Asymptotic Notations for Analysis of AlgorithmsWe have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don't depend on machine-specific constants and don't require algorithms to be implemented and time taken by programs 8 min read Data StructuresArray Data Structure GuideIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 3 min read String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut 2 min read Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The 2 min read Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List: 2 min read Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first 2 min read Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems 2 min read Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most 4 min read Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of 3 min read Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this 15+ min read AlgorithmsSearching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input 2 min read Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution 14 min read Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get 3 min read Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net 3 min read Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of 3 min read Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit 4 min read AdvancedSegment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree 3 min read Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i 2 min read GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br 2 min read Interview PreparationInterview Corner: All Resources To Crack Any Tech InterviewThis article serves as your one-stop guide to interview preparation, designed to help you succeed across different experience levels and company expectations. Here is what you should expect in a Tech Interview, please remember the following points:Tech Interview Preparation does not have any fixed s 3 min read GfG160 - 160 Days of Problem SolvingAre you preparing for technical interviews and would like to be well-structured to improve your problem-solving skills? Well, we have good news for you! GeeksforGeeks proudly presents GfG160, a 160-day coding challenge starting on 15th November 2024. In this event, we will provide daily coding probl 3 min read Practice ProblemGeeksforGeeks Practice - Leading Online Coding PlatformGeeksforGeeks Practice is an online coding platform designed to help developers and students practice coding online and sharpen their programming skills with the following features. GfG 160: This consists of most popular interview problems organized topic wise and difficulty with with well written e 6 min read Problem of The Day - Develop the Habit of CodingDo you find it difficult to develop a habit of Coding? If yes, then we have a most effective solution for you - all you geeks need to do is solve one programming problem each day without any break, and BOOM, the results will surprise you! Let us tell you how:Suppose you commit to improve yourself an 5 min read Like