You are on page 1of 35

DSA Interview Problems on Stack Practice Stack MCQs on Stack Stack Tutorial Stack Operations Stack Imp

Design and Implement Special Stack Data


Structure | Added Space Optimized Version
Question: Design a Data Structure SpecialStack that supports all the stack
operations like push(), pop(), isEmpty(), isFull() and an additional operation
getMin() which should return minimum element from the SpecialStack. All
these operations of SpecialStack must be O(1). To implement SpecialStack,
you should only use standard Stack data structure and no other data structure
like arrays, list, . etc.

Example:

Consider the following SpecialStack


16 --> TOP
15
29
19
18

When getMin() is called it should


return 15, which is the minimum
element in the current stack.

If we do pop two times on stack,


the stack becomes
29 --> TOP
19
18

When getMin() is called, it should


return 18 which is the minimum in
the current stack.

Recommended Problem

Special Stack Solve Problem


Stack STL +1 more Paytm VMWare +11 more
Submission count: 81.5K
We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Solution:

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.

Push(int x) // inserts an element x to Special Stack

1. 1) push x to the first stack (the stack with actual elements)


2. 2) compare x with the top element of the second stack (the auxiliary stack).
Let the top element be y.
1. If x is smaller than y then push x to the auxiliary stack.
2. If x is greater than y then push y to the auxiliary stack.

int Pop() // removes an element from Special Stack and return the removed
element

1. pop the top element from the auxiliary stack.


2. pop the top element from the actual stack and return it. Step 1 is necessary
to make sure that the auxiliary stack is also updated for future operations.

int getMin() // returns the minimum element from Special Stack

1. Return the top element of the auxiliary stack.

We can see that all the above operations are O(1).

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

When 19 is inserted, both stacks change to following.


Actual Stack
19 <--- top
18
Auxiliary Stack
18 <---- top
18

When 29 is inserted, both stacks change to following.


Actual Stack
29 <--- top
19
18
Auxiliary Stack
18 <---- top
18
18

When 15 is inserted, both stacks change to following.


Actual Stack
15 <--- top
29
19
18
Auxiliary Stack
15 <---- top
18
18
18

When 16 is inserted, both stacks change to following.


Actual Stack
16 <--- top
15
29
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you19acknowledge that you have read and understood our Cookie Policy & Privacy Policy
18
Auxiliary Stack
15 <---- top
15
18
18
18

The following is the implementation for SpecialStack class. In the below


implementation, SpecialStack inherits from Stack and has one Stack object min
which works as an auxiliary stack.

C++

#include <iostream>
#include <stdlib.h>

using namespace std;

/* A simple stack class with


basic stack functionalities */
class Stack {
private:
static const int max = 100;
int arr[max];
int top;

public:
Stack() { top = -1; }
bool isEmpty();
bool isFull();
int pop();
void push(int x);
};

/* Stack's member method to check


if the stack is empty */
bool Stack::isEmpty()
{
if (top == -1)
return true;
return false;
}

/* Stack's member method to check


if the stack is full */
bool Stack::isFull()
{
We use cookies
if to(top
ensure==youmax
have- the
1)best browsing experience on our website. By using our
site, you acknowledge
return true; read and understood our Cookie Policy & Privacy Policy
that you have
return false;
}

/* Stack's member method to remove


an element from it */
int Stack::pop()
{
if (isEmpty()) {
cout << "Stack Underflow";
abort();
}
int x = arr[top];
top--;
return x;
}

/* Stack's member method to insert


an element to it */
void Stack::push(int x)
{
if (isFull()) {
cout << "Stack Overflow";
abort();
}
top++;
arr[top] = x;
}

/* A class that supports all the stack


operations and one additional
operation getMin() that returns the
minimum element from stack at
any time. This class inherits from
the stack class and uses an
auxiliary stack that holds minimum
elements */
class SpecialStack : public Stack {
Stack min;

public:
int pop();
void push(int x);
int getMin();
};

/* 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 */
void SpecialStack::push(int x)
{
We use cookies
if to(isEmpty()
ensure you have
== the best browsing
true) { experience on our website. By using our
site, you acknowledge that you have
Stack::push(x); read and understood our Cookie Policy & Privacy Policy
min.push(x);
}
else {
Stack::push(x);
int y = min.pop();
min.push(y);
if (x < y)
min.push(x);
else
min.push(y);
}
}

/* SpecialStack's member method to


remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
int x = Stack::pop();
min.pop();
return x;
}

/* SpecialStack's member method to get


minimum element from it. */
int SpecialStack::getMin()
{
int x = min.pop();
min.push(x);
return x;
}

/* Driver program to test SpecialStack


methods */
int main()
{
SpecialStack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.getMin() << endl;
s.push(5);
cout << s.getMin();
return 0;
}

Java

// Java implementation of SpecialStack


// Note : here we use Stack class for
// Stack implementation
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
import java.util.Stack;
/* A class that supports all the
stack operations and one additional
operation getMin() that returns
the minimum element from stack at
any time. This class inherits from
the stack class and uses an
auxiliary stack that holds minimum
elements */

class SpecialStack extends Stack<Integer> {


Stack<Integer> min = new Stack<>();

/* 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 */
void push(int x)
{
if (isEmpty() == true) {
super.push(x);
min.push(x);
}
else {
super.push(x);
int y = min.pop();
min.push(y);
if (x < y)
min.push(x);
else
min.push(y);
}
}

/* 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 */
public Integer pop()
{
int x = super.pop();
min.pop();
return x;
}

/* SpecialStack's member method to get


minimum element from it. */
int getMin()
{
int x = min.pop();
We use cookies tomin.push(x);
ensure you have the best browsing experience on our website. By using our
site, you acknowledge that x;
return you have read and understood our Cookie Policy & Privacy Policy
}

/* Driver program to test SpecialStack


methods */
public static void main(String[] args)
{
SpecialStack s = new SpecialStack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.getMin());
s.push(5);
System.out.println(s.getMin());
}
}
// This code is contributed by Sumit Ghosh

Python3

# Python3 program for the


# above approach
# A simple stack class with
# basic stack functionalities
class stack:

def __init__(self):

self.array = []
self.top = -1
self.max = 100

# Stack's member method to check


# if the stack is empty
def isEmpty(self):

if self.top == -1:
return True
else:
return False

# Stack's member method to check


# if the stack is full
def isFull(self):

if self.top == self.max - 1:
return True
else:
return False

# Stack's member method to


# insert an element to it
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you def
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
push(self, data):
if self.isFull():
print('Stack OverFlow')
return
else:
self.top += 1
self.array.append(data)

# Stack's member method to


# remove an element from it
def pop(self):

if self.isEmpty():
print('Stack UnderFlow')
return
else:
self.top -= 1
return self.array.pop()

# A class that supports all the stack


# operations and one additional
# operation getMin() that returns the
# minimum element from stack at
# any time. This class inherits from
# the stack class and uses an
# auxiliary stack that holds
# minimum elements
class SpecialStack(stack):

def __init__(self):
super().__init__()
self.Min = stack()

# 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
def push(self, x):

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)

We use cookies to ensure you havemember


# SpecialStack's the bestmethod
browsingto
experience on our website. By using our
site, you #acknowledge
remove an element from it. This our Cookie Policy & Privacy Policy
that you have read and understood
# method removes top element from
# min stack also.
def pop(self):

x = super().pop()
self.Min.pop()
return x

# SpecialStack's member method


# to get minimum element from it.
def getmin(self):

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())

# This code is contributed by rachitkatiyar99

C#

using System;
using System.Collections.Generic;

// A class that supports all the stack operations


// and one additional operation `GetMin`
// that returns the minimum element from the stack at any time.
// This class inherits from the `Stack` class and uses an
// auxiliary stack to hold minimum elements.
class SpecialStack : Stack<int>
{
// Auxiliary stack to store minimum elements.
Stack<int> min = new Stack<int>();

// Method to insert an element to the stack.


// Makes sure that the min stack is also updated
// with appropriate minimum values.
public void Push(int x)
{
if (Count == 0)
{
We use cookies to ensure you have the best browsing experience on our website. By using our
// If the stack is empty, simply add the
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
// element and push it to the `min` stack.
base.Push(x);
min.Push(x);
}
else
{
// Add the element to the stack.
base.Push(x);
int y = min.Pop();
min.Push(y);

// If the current element is less than the current minimum,


// add it to the `min` stack.
if (x < y)
min.Push(x);
else
min.Push(y);
}
}

// Method to remove an element from the stack.


// Makes sure that the min stack is also updated with
// appropriate minimum values.
public new int Pop()
{
// Pop the element from the stack.
int x = base.Pop();

// Pop the minimum value from the `min` stack.


min.Pop();

return x;
}

// Method to get the minimum element from the stack.


public int GetMin()
{
int x = min.Pop();
min.Push(x);
return x;
}

static void Main(string[] args)


{
SpecialStack s = new SpecialStack();
s.Push(10);
s.Push(20);
s.Push(30);
Console.WriteLine(s.GetMin());
s.Push(5);
Console.WriteLine(s.GetMin());
Console.ReadLine();
}
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
Javascript

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();
}
}
}

class SpecialStack extends stack {


constructor() {
super();
this.Min = new stack();
}
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you push(x)
acknowledge
{ that you have read and understood our Cookie Policy & Privacy Policy
if (this.isEmpty()) {
super.push(x);
this.Min.push(x);
} else {
super.push(x);
let y = this.Min.pop();
this.Min.push(y);
if (x <= y) {
this.Min.push(x);
} else {
this.Min.push(y);
}
}
}

pop() {
let x = super.pop();
this.Min.pop();
return x;
}

getmin() {
let x = this.Min.pop();
this.Min.push(x);
return x;
}
}

let s = new SpecialStack();


s.push(10);
s.push(20);
s.push(30);
console.log(s.getmin());
s.push(5);
console.log(s.getmin());

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)

Auxiliary Space: O(n).


Use of auxiliary stack for storing values.

Space Optimized Version

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++

/* 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 */
void SpecialStack::push(int x)
{
if (isEmpty() == true) {
Stack::push(x);
min.push(x);
}
else {
Stack::push(x);
int y = min.pop();
min.push(y);

/* push only when the incoming element


of main stack is smaller
than or equal to top of auxiliary stack */
if (x <= y)
min.push(x);
}
}

/* SpecialStack's member method to


remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
We use cookies
intto xensure you have the best browsing experience on our website. By using our
= Stack::pop();
site, you acknowledge
int y = that you have read and understood our Cookie Policy & Privacy Policy
min.pop();
/* Push the popped element y back
only if it is not equal to x */
if (y != x)
min.push(y);

return x;
}

Java

/* 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 */

void push(int x)
{
if (isEmpty() == true) {
super.push(x);
min.push(x);
}
else {
super.push(x);
int y = min.pop();
min.push(y);

/* push only when the incoming


element of main stack is smaller
than or equal to top of auxiliary stack */
if (x <= y)
min.push(x);
}
}

/* SpecialStack's member method to


remove an element from it. This method
removes top element from min stack also. */
public Integer pop()
{
int x = super.pop();
int y = min.pop();

/* Push the popped element y back


only if it is not equal to x */
if (y != x)
min.push(y);
return x;
}

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

''' 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 '''

def push(x):
if (isEmpty() == True):
super.append(x);
min.append(x);

else:
super.append(x);
y = min.pop();
min.append(y);

''' push only when the incoming


element of main stack is smaller
than or equal to top of auxiliary stack '''
if (x <= y):
min.append(x);

''' SpecialStack's member method to


remove an element from it. This method
removes top element from min stack also. '''
def pop():
x = super.pop();
y = min.pop();

''' Push the popped element y back


only if it is not equal to x '''
if (y != x):
min.append(y);
return x;

# This code contributed by umadevi9616

C#

/* 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 */
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge
void push(intthatx)
you have read and understood our Cookie Policy & Privacy Policy
{
if (min.Count==0) {
super.Push(x);
min.Push(x);
}
else {
super.Push(x);
int y = min.Pop();
min.Push(y);

/* push only when the incoming


element of main stack is smaller
than or equal to top of auxiliary stack */
if (x <= y)
min.Push(x);
}
}

/* SpecialStack's member method to


remove an element from it. This method
removes top element from min stack also. */
public int pop()
{
int x = super.Pop();
int y = min.Pop();

/* Push the popped element y back


only if it is not equal to x */
if (y != x)
min.Push(y);
return x;
}

// This code is contributed by umadevi9616

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);

/* push only when the incoming


element of main stack is smaller
than or equal to top of auxiliary stack */
if (x <= y)
min.push(x);
}
}

/* SpecialStack's member method to


remove an element from it. This method
removes top element from min stack also. */
function pop()
{
var x = super.pop();
var y = min.pop();

/* Push the popped element y back


only if it is not equal to x */
if (y != x)
min.push(y);
return x;
}

// This code is contributed by umadevi9616


</script>

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)

Auxiliary Space: O(n).


The complexity in the worst case is the same as above but in other cases, it
will take slightly less space than the above approach as repetition is
neglected.

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).

Note: Following method will fail if we try to insert DUMMY_VALUE in the


stack, so we have to make our selection of DUMMY_VALUE carefully.
Let’s say the following elements are being inserted in the stack – 3 2 6 1 8 5

d is dummy value.

s is wrapper stack

top is top element of the 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;

/* A special stack having peek() pop() and


* push() along with additional getMin() that
* returns minimum value in a stack without
* using extra space and all operations in O(1)
* time.. ???? */
class SpecialStack
{

// Sentinel value for min


int min = -1;

// DEMO_VALUE
static const int demoVal = 9999;
stack<int> st;

public:

void getMin()
{
cout << "min is: " << min << endl;
}

void push(int val)


{

// If stack is empty OR current element


// is less than min, update min.
if (st.empty() || val < min)
{
min = val;
}
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
// Encode the current value with
// demoVal, combine with min and
// insert into stack
st.push(val * demoVal + min);
cout << "pushed: " << val << endl;
}

int pop()
{
// if stack is empty return -1;
if ( st.empty() ) {
cout << "stack underflow" << endl ;
return -1;
}

int val = st.top();


st.pop();

// If stack is empty, there would


// be no min value present, so
// make min as -1
if (!st.empty())
min = st.top() % demoVal;
else
min = -1;

cout << "popped: " << val / demoVal << endl;

// Decode actual value from


// encoded value
return val / demoVal;
}

int peek()
{

// Decode actual value


// from encoded value
return st.top() / demoVal;
}
};

// Driver Code
int main()
{
SpecialStack s;

vector<int> arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 };

for(int i = 0; i < arr.size(); i++)


{
s.push(arr[i]);
s.getMin();
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
cout << endl;
for(int i = 0; i < arr.size(); i++)
{
s.pop();
s.getMin();
}
return 0;
}

// This code is contributed by scisaif

Java

import java.util.Stack;

/* A special stack having peek() pop() and push() along with


* additional getMin() that returns minimum value in a stack
* without using extra space and all operations in O(1)
* time..
* */
public class SpecialStack {

int min = -1; // sentinel value for min


static int demoVal = 9999; // DEMO_VALUE
Stack<Integer> st = new Stack<Integer>();

void getMin() { System.out.println("min is: " + min); }

void push(int val)


{
// if stack is empty OR current element is less than
// min, update min..
if (st.isEmpty() || val < min) {
min = val;
}

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;
}

We use cookies toint


ensureval
you=have the best browsing experience on our website. By using our
st.pop();
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
if (!st.isEmpty()) // if stack is empty, there would
// be no min value present, so
// make min as -1
min = st.peek() % demoVal;
else
min = -1;
System.out.println("popped: " + val / demoVal);
return val / demoVal; // decode actual value from
// encoded value
}

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 };

for (int i = 0; i < arr.length; i++) {


s.push(arr[i]);
s.getMin();
}
System.out.println();
for (int i = 0; i < arr.length; i++) {
s.pop();
s.getMin();
}
}
}

Python3

# A special stack having peek() pop() and


# push() along with additional getMin() that
# returns minimum value in a stack without
# using extra space and all operations in O(1)
# time.. ????
class SpecialStack:

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 push(self, val):

# If stack is empty OR current element


# is less than min, update min.
if len(self.st) == 0 or val < self.minm:
self.minm = val

# Encode the current value with


# demoVal, combine with min and
# insert into stack
self.st.append(val*self.demoVal + self.minm)
print("pushed: ", val)

def pop(self):

# if stack is empty return -1


if len(self.st) == 0:
print("stack underflow")
return -1

val = self.st.pop()

# If stack is empty, there would


# be no min value present, so
# make min as -1
if len(self.st) != 0:
self.minm = self.st[-1] % self.demoVal
else:
self.minm = -1

print("popped: ", val // self.demoVal)

# Decode actual value from


# encoded value
return val // self.demoVal

def peek(self):

# Decode actual value


# from encoded value
return self.st[-1] // self.demoVal

# 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()

# This code is contributed by pankajkumar70792.

C#

using System;
using System.Collections.Generic;

/* A special stack having peek() pop() and push() along with


* additional getMin() that returns minimum value in a stack
* without using extra space and all operations in O(1)
* time..
* */
public class SpecialStack {

int min = -1; // sentinel value for min


static int demoVal = 9999; // DEMO_VALUE
Stack<int> st = new Stack<int>();

void getMin() { Console.WriteLine("min is: " + min); }

void push(int val)


{
// if stack is empty OR current element is less than
// min, update min..
if (st.Count==0 || val < min) {
min = val;
}

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 val = st.Pop();


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
if (st.Count!=0) // if stack is empty, there would
// be no min value present, so
// make min as -1
min = st.Peek() % demoVal;
else
min = -1;
Console.WriteLine("popped: " + val / demoVal);
return val / demoVal; // decode actual value from
// encoded value
}

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 };

for (int i = 0; i < arr.Length; i++) {


s.push(arr[i]);
s.getMin();
}
Console.WriteLine();
for (int i = 0; i < arr.Length; i++) {
s.pop();
s.getMin();
}
}
}

// This code is contributed by gauravrajput1

Javascript

/* A special stack having peek() pop() and


* push() along with additional getMin() that
* returns minimum value in a stack without
* using extra space and all operations in O(1)
* time.. ???? */

class SpecialStack
{
constructor(){
// Sentinel value for min
this.min = -1;

We use cookies to//


ensure you have the best browsing experience on our website. By using our
Demo value
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
this.demoVal = 9999;
this.st = [];
}

getMin()
{
console.log("min is: ", this.min);
}

push(val)
{

// If stack is empty OR current element


// is less than min, update min.
if ((this.st.length == 0) || (val < this.min))
{
this.min = val;
}

// Encode the current value with


// demoVal, combine with min and
// insert into stack
this.st.push(val * this.demoVal + this.min);
console.log("pushed: ", val);
}

pop()
{
// if stack is empty return -1;
if (this.st.length == 0) {
console.log("stack underflow");
return -1;
}

let val = this.st[this.st.length - 1];


this.st.pop();

// If stack is empty, there would


// be no min value present, so
// make min as -1
if (this.st.length){
this.min = this.st[this.st.length - 1]% this.demoVal;
}
else{
this.min = -1;
}

console.log("popped: ", Math.floor(val / this.demoVal));

// Decode actual value from


// encoded value
return Math.floor(val / this.demoVal);
}
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge
peek() that you have read and understood our Cookie Policy & Privacy Policy
{

// Decode actual value


// from encoded value
return Math.floor(this.st[this.st.length - 1] / demoVal);
}
};

// Driver Code
let s = new SpecialStack();

let arr = [3, 2, 6, 1, 8, 5, 5, 5, 5 ];

for(let i = 0; i < arr.length; i++)


{
s.push(arr[i]);
s.getMin();
}

console.log();

for(let i = 0; i < arr.length; i++)


{
s.pop();
s.getMin();
}

// This code is contributed by Nidhi goel.

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)

Auxiliary Space: O(1). No extra space is used.

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.

Last Updated : 20 Feb, 2023 162

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

Print Longest Bitonic subsequence Word Wrap problem ( Space optimized


(Space Optimized Approach) solution )

Printing Matrix Chain Multiplication (A Vertical Sum in Binary Tree | Set 2 (Space
Space Optimized Solution) Optimized)

A Space Optimized Solution of LCS A Space Optimized DP solution for 0-1


Knapsack Problem

Implement Dynamic Multi Stack (K Design a stack to retrieve original


stacks) using only one Data Structure elements and return the minimum
element in O(1) time and O(1) space

Complete Tutorials
Learn Algorithms with Javascript | DSA DSA Crash Course | Revision Checklist
using JavaScript Tutorial with Interview Guide

Learn Data Structures and Algorithms | Mathematical and Geometric Algorithms


DSA Tutorial - Data Structure and Algorithm Tutorials

Learn Data Structures with Javascript |


DSA using JavaScript Tutorial

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

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305

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

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial Web Templates
ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design

Python Computer Science


Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Python Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
AWS Top 50 Tree
Docker Top 50 Graph
Kubernetes Top 50 Array
Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

System Design JavaScript


High Level Design JavaScript Examples
Low Level Design TypeScript
We use cookies to ensureUML
you have the best browsing experience on our website. By using ourReactJS
Diagrams
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

NCERT Solutions School Subjects


Class 12 Mathematics
Class 11 Physics
Class 10 Chemistry
Class 9 Biology
Class 8 Social Science
Complete Study Material English Grammar

Commerce UPSC Study Material


Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Management Science and Technology Notes
HR Management Economy Notes
Finance Ethics Notes
Income Tax Previous Year Papers

SSC/ BANKING Colleges


SSC CGL Syllabus Indian Colleges Admission & Campus Experiences
SBI PO Syllabus List of Central Universities - In India
SBI Clerk Syllabus Colleges in Delhi University
IBPS PO Syllabus IIT Colleges
IBPS Clerk Syllabus NIT Colleges
SSC CGL Practice Papers IIIT Colleges

Companies Preparation Corner


META Owned Companies Company-Wise Recruitment Process
Alphabhet Owned Companies Resume Templates
TATA Group Owned Companies Aptitude Preparation
Reliance Owned Companies Puzzles
Fintech Companies Company-Wise Preparation
We use cookies to ensure you have
EdTech the best browsing experience on our website. By using our
Companies
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Exams More Tutorials
JEE Mains Software Development
JEE Advanced Software Testing
GATE CS Product Management
NEET SAP
UGC NET SEO - Search Engine Optimization
Linux
Excel

Free Online Tools Write & Earn


Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

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

You might also like