Professional Documents
Culture Documents
Example:
Recommended Problem
Use two stacks: one to store actual stack elements and the other as an
auxiliary stack to store minimum values. The idea is to do push() and pop()
operations in such a way that the top of the auxiliary stack is always the
minimum. Let us see how push() and pop() operations work.
int Pop() // removes an element from Special Stack and return the removed
element
Let us see an example. Let us assume that both stacks are initially empty and
18, 19, 29, 15, and 16 are inserted to the SpecialStack.
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
When we insert 18, both stacks change to following.
Actual Stack
18 <--- top
Auxiliary Stack
18 <---- top
C++
#include <iostream>
#include <stdlib.h>
public:
Stack() { top = -1; }
bool isEmpty();
bool isFull();
int pop();
void push(int x);
};
public:
int pop();
void push(int x);
int getMin();
};
Java
Python3
def __init__(self):
self.array = []
self.top = -1
self.max = 100
if self.top == -1:
return True
else:
return False
if self.top == self.max - 1:
return True
else:
return False
if self.isEmpty():
print('Stack UnderFlow')
return
else:
self.top -= 1
return self.array.pop()
def __init__(self):
super().__init__()
self.Min = stack()
if self.isEmpty():
super().push(x)
self.Min.push(x)
else:
super().push(x)
y = self.Min.pop()
self.Min.push(y)
if x <= y:
self.Min.push(x)
else:
self.Min.push(y)
x = super().pop()
self.Min.pop()
return x
x = self.Min.pop()
self.Min.push(x)
return x
# Driver code
if __name__ == '__main__':
s = SpecialStack()
s.push(10)
s.push(20)
s.push(30)
print(s.getmin())
s.push(5)
print(s.getmin())
C#
using System;
using System.Collections.Generic;
return x;
}
class stack {
constructor() {
this.array = [];
this.top = -1;
this.max = 100;
}
isEmpty() {
if (this.top == -1) {
return true;
} else {
return false;
}
}
isFull() {
if (this.top == this.max - 1) {
return true;
} else {
return false;
}
}
push(data) {
if (this.isFull()) {
console.log("Stack OverFlow");
return;
} else {
this.top += 1;
this.array.push(data);
}
}
pop() {
if (this.isEmpty()) {
console.log("Stack UnderFlow");
return;
} else {
this.top -= 1;
return this.array.pop();
}
}
}
pop() {
let x = super.pop();
this.Min.pop();
return x;
}
getmin() {
let x = this.Min.pop();
this.Min.push(x);
return x;
}
}
Output
10
5
Complexity Analysis:
Time Complexity:
1. For insert operation: O(1) (As insertion ‘push’ in a stack takes constant
time)
2. For delete operation: O(1) (As deletion ‘pop’ in a stack takes constant
We use cookies to ensure you have the best browsing experience on our website. By using our
time) that you have read and understood our Cookie Policy & Privacy Policy
site, you acknowledge
3. For ‘Get Min’ operation: O(1) (As we have used an auxiliary stack which
has it’s top as the minimum element)
The above approach can be optimized. We can limit the number of elements in
the auxiliary stack. We can push only when the incoming element of the main
stack is smaller than or equal to the top of the auxiliary stack. Similarly during
pop, if the pop-off element equal to the top of the auxiliary stack, remove the
top element of the auxiliary stack. Following is the modified implementation of
push() and pop().
C++
return x;
}
Java
void push(int x)
{
if (isEmpty() == true) {
super.push(x);
min.push(x);
}
else {
super.push(x);
int y = min.pop();
min.push(y);
We use//cookies to ensure you have the best browsing experience on our website. By using our
This code is contributed by Sumit Ghosh
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Python3
def push(x):
if (isEmpty() == True):
super.append(x);
min.append(x);
else:
super.append(x);
y = min.pop();
min.append(y);
C#
Javascript
<script>
/* SpecialStack's member method to
insert an element to it. This method
makes sure that the min stack is
also updated with appropriate minimum
values */
function push(x)
{
if (isEmpty() == true) {
super.push(x);
min.push(x);
}
else {
We use cookies tosuper.push(x);
ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
var y = min.pop();
min.push(y);
Complexity Analysis:
Time Complexity:
1. For Insert operation: O(1) (As insertion ‘push’ in a stack takes constant
time)
2. For Delete operation: O(1) (As deletion ‘pop’ in a stack takes constant
time)
3. For ‘Get Min’ operation: O(1) (As we have used an auxiliary which has
it’s top as the minimum element)
Further optimized O(1) time complexity and O(1) space complexity solution
:
We useThe above
cookies approach
to ensure can
you have the bestbe optimized
browsing further
experience and the
on our website. solution
By using our can be made to
site, you
workacknowledge
in O(1)that you complexity
time have read and understood
and O(1) ourspace
Cookie Policy & Privacy Policy
complexity. The idea is to store
min element found till current insertion) along with all the elements as a
reminder of a DUMMY_VALUE, and the actual element as a multiple of the
DUMMY_VALUE.
For example, while pushing an element ‘e’ into the stack, store it as (e *
DUMMY_VALUE + minFoundSoFar), this way we know what was the
minimum value present in the stack at the time ‘e’ was being inserted.
To pop the actual value just return e/DUMMY_VALUE and set the new
minimum as (minFoundSoFar % DUMMY_VALUE).
d is dummy value.
s is wrapper stack
min is the minimum value at that instant when the elements were
inserted/removed
The following steps shows the current state of the above variables at any
instant –
1. s.push(3);
min=3 //updated min as stack here is empty
s = {3*d + 3}
top = (3*d + 3)/d = 3
2. s.push(2);
min = 2 //updated min as min > current element
s = {3*d + 3-> 2*d + 2}
top = (2*d + 2)/d = 2
3. s.push(6);
min = 2
s = {3*d + 3-> 2*d + 2-> 6*d + 2}
top = (6*d + 2)/d = 6
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
4. s.push(1);
min = 1 //updated min as min > current element
s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1}
top = (1*d + 1)/d = 1
5. s.push(8);
min = 1
s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}
top = (8*d + 1)/d = 8
6. s.push(5);
min = 1
s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}
top = (5*d + 1)/d = 5
7. s.pop();
s = {3*d + 3 -> 2*d + 2 -> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}
top = (5*d + 1)/d = 5
min = (8*d + 1)%d = 1 // min is always remainder of the second top
element in stack.
8. s.pop();
s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}
top = (8*d + 1)/d = 8
min = (1*d + 1)%d = 1
9. s.pop()
s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1}
top = (1*d + 1)/d = 1
min = (6*d + 2)%d = 2
10. s.pop()
s = {3*d + 3-> 2*d + 2-> 6*d + 2}
top = (6*d + 2)/d = 6
min = (2*d + 2)%d = 2
11. s.pop()
We use cookiess to=ensure
{3*d you have the
+ 3-> 2*dbest
+ browsing
2} experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
top = (2*d + 2)/d = 2
min = (3*d + 3)%d = 3
12. s.pop()
s = {3*d + 3}
top = (3*d + 3)/d = 3
min = -1 // since stack is now empty
C++
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
// DEMO_VALUE
static const int demoVal = 9999;
stack<int> st;
public:
void getMin()
{
cout << "min is: " << min << endl;
}
int pop()
{
// if stack is empty return -1;
if ( st.empty() ) {
cout << "stack underflow" << endl ;
return -1;
}
int peek()
{
// Driver Code
int main()
{
SpecialStack s;
vector<int> arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 };
Java
import java.util.Stack;
st.push(val * demoVal
+ min); // encode the current value with
// demoVal, combine with min and
// insert into stack
System.out.println("pushed: " + val);
}
int pop()
{
// if stack is empty return -1;
if (st.isEmpty() ) {
System.out.println("stack underflow");
return -1;
}
int peek()
{
return st.peek() / demoVal; // decode actual value
// from encoded value
}
// Driver Code
public static void main(String[] args)
{
SpecialStack s = new SpecialStack();
int[] arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 };
Python3
def __init__(self):
# Sentinel value for min
self.minm = -1
# DEMO_VALUE
SpecialStack.demoVal = 9999
We use cookies toself.st
ensure you=have
[]
the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
def getMin(self):
print("min is: ", self.minm)
def pop(self):
val = self.st.pop()
def peek(self):
# Driver Code
if __name__ == "__main__":
s = SpecialStack()
arr = [3, 2, 6, 1, 8, 5, 5, 5, 5]
for i in range(len(arr)):
We use cookies tos.push(arr[i])
ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
s.getMin()
print("\n")
for i in range(len(arr)):
s.pop()
s.getMin()
C#
using System;
using System.Collections.Generic;
st.Push(val * demoVal
+ min); // encode the current value with
// demoVal, combine with min and
// insert into stack
Console.WriteLine("pushed: " + val);
}
int pop()
{
// if stack is empty return -1;
if (st.Count==0 ) {
Console.WriteLine("stack underflow");
return -1;
}
int peek()
{
return st.Peek() / demoVal; // decode actual value
// from encoded value
}
// Driver Code
public static void Main(String[] args)
{
SpecialStack s = new SpecialStack();
int[] arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 };
Javascript
class SpecialStack
{
constructor(){
// Sentinel value for min
this.min = -1;
getMin()
{
console.log("min is: ", this.min);
}
push(val)
{
pop()
{
// if stack is empty return -1;
if (this.st.length == 0) {
console.log("stack underflow");
return -1;
}
// Driver Code
let s = new SpecialStack();
console.log();
Output
pushed: 3
min is: 3
pushed: 2
min is: 2
pushed: 6
min is: 2
pushed: 1
min is: 1
pushed: 8
min is: 1
pushed: 5
min is: 1
pushed: 5
min is: 1
pushed:
We use cookies 5 you have the best browsing experience on our website. By using our
to ensure
site, youmin
acknowledge
is: 1 that you have read and understood our Cookie Policy & Privacy Policy
pushed: 5
min is: 1
popped: 5
min is: 1
popped: 5
min is: 1
popped: 5
min is: 1
popped: 5
min is: 1
popped: 8
min is: 1
popped: 1
min is: 2
popped: 6
min is: 2
popped: 2
min is: 3
popped: 3
min is: -1
Complexity Analysis:
For push() operation: O(1) (As insertion ‘push’ in a stack takes constant time)
For pop() operation: O(1) (As pop operation in a stack takes constant time)
For ‘Get Min’ operation: O(1) (As we have maintained min variable throughout
the code)
Design a stack that supports getMin() in O(1) time and O(1) extra space
Thanks to @Venki, @swarup, and @Jing Huang for their inputs.
Please write comments if you find the above code incorrect, or find other ways
to solve the same problem.
Previous Next
We use cookies to ensure you have the best browsing experience on our website. By using our
Stack
site, you in Scalathat you have read and understood our Cookie Policy
acknowledge Implement two Stacks in an Array
& Privacy Policy
Share your thoughts in the comments Add Your Comment
Similar Reads
Longest Common Substring (Space Number of n digit stepping numbers |
optimized DP solution) Space optimized solution
Printing Matrix Chain Multiplication (A Vertical Sum in Binary Tree | Set 2 (Space
Space Optimized Solution) Optimized)
Complete Tutorials
Learn Algorithms with Javascript | DSA DSA Crash Course | Revision Checklist
using JavaScript Tutorial with Interview Guide
GeeksforGeeks
Article Tags : Adobe , Amazon , Linkedin , Paytm , STL , VMWare , DSA , Stack
Practice Tags : Adobe, Amazon, Linkedin, Paytm, VMWare, Stack, STL
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Additional Information
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
We use cookies to ensure youGoLang
have the best browsing experience on our website. By usingDSA
our Roadmap
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy