• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Get Minimum element in O(1) from input numbers or Stack

August 16, 2014 by Dhaval Dave

Question : Get Minimum element in O(1) from Input Numbers or Stack

– With any traditional way we can’t get minimum element in O(1)
– so we need to come up with different data structure.
– As its very old and famous question We are directly explaining logic

Logic 1)
Keep Two Stacks A and B.
A will contain all numbers which are input by users.
B will contain only minimum number from all input numbers.
ex. Input 10,20,5,30,2

Consider the following input
A                        B  (minimum elements)
2  --> TOP               2   ...
30                       5   ...
5                        5  (smallest in 10,20,5 input)
20                       10 (smallest in 10,20 input)
10                       10 (smallest at beginning)
so as shown in figure B (minimum element stack will keep all smallest numbers wrt input)

Pros
– storing minimum element for each input.
– if current minimum element is popped , we still have minimum element in present stack

Cons
– O(n) Extra Space.

Code :

#include<iostream>
#include<stdlib.h>
using namespace std;
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);
};
bool Stack::isEmpty()
{
    if(top == -1)
        return true;
    return false;
}
bool Stack::isFull()
{
    if(top == max - 1)
        return true;
    return false;
}
int Stack::pop()
{
    if(isEmpty())
    {
        cout<<"Stack Underflow";
        abort();
    }
    int x = arr[top];
    top--;
    return x;
}
void Stack::push(int x)
{
    if(isFull())
    {
        cout<<"Stack Overflow";
        abort();
    }
    top++;
    arr[top] = x;
}
//Stack

class SpecialStack: public Stack
{
    Stack min;
public:
    int pop();
    void push(int x);
    int getMin();
};
 
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);
        if( x < y )
          min.push(x);
        else
          min.push(y);
    }
}
int SpecialStack::pop()
{
    int x = Stack::pop();
    min.pop();
    return x;
}
int SpecialStack::getMin()
{
    int x = min.pop();
    min.push(x);
    return x;
}
int main()
{
    SpecialStack s;
    s.push(10);
    s.push(5);
    s.push(20);
    s.push(30);
    cout<<s.getMin()<<endl;
    s.push(1);
    cout<<s.getMin();
    return 0;
}

C Working Code : Find here : http://ideone.com/qOtFoG
C++ Working code : Find here : http://ideone.com/mgtTQY

Logic 2)

To Get Minimum element in O(1) from Input or Stack,  Instead of keeping a stack of minimum elements in B, we can optimism the space complexity for above solution with single minimum number.

Consider the following input
A                        B  (minimum elements)
2  --> TOP               
30                       
5                        2  
20                       5 
10                       10 (smallest at beginning)

If You pop from A, Pop from B (min elem stack as well) and both’s data is not matching, Push B’s top element to B.
Consider sequence
Pop A. So popped element from A is 2, and B’s popped element is 2. so now min element is for now on is 5.
Pop A, So popped element from A is 30 and B’s popped element is 5, both are not matching, so push 5 to B again. so in B elements are 5,10 and will be min element.

Code :

In above C++ code, change these two methods Push and Pop

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);
  
        if( x <= y )
            min.push(x);
    }
}
 
int SpecialStack::pop()
{
    int x = Stack::pop();
    int y = min.pop(); 
    if ( y != x )
        min.push(y);
    return x;
}

Similar Articles

Filed Under: Adobe Interview Questions, Amazon Interview Question, Flipkart Interview Questions, Interview Questions, Microsoft Interview Questions, problem Tagged With: Array, Stack

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Find an index i such that Arr [i] = i in array of n distinct integers sorted in ascending order.

Wrong Directions given find minimum moves so that he can reach to the destination

write a c program that given a set a of n numbers and another number x determines whether or not there exist two elements in s whose sum is exactly x

Trapping Rain Water

Amazon Interview On-Campus For Internship – 1

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Daughter’s Age VeryGood Puzzle

Check a String is SUBSEQUENCE of another String Find Minimum length for that ( DNA Matching )

Binary Tree Isomorphic to each other

Sequence Finder Dynamic Programming

Client Server C program

Apriori algorithm C Code Data Mining

Maximum difference between two elements s.t larger element appears after the smaller number

25 horses 5 tracks Find 3 fastest puzzle

Closed Parentheses checker

Walmart Labs Interview Experience

Urban Ladder Written Test.

Inorder and Preorder traversals of a Binary Tree given. Output the Postorder traversal of it.

How Radix sort works

Maximum of all subarrays of size k

Calculate price of parking from parking start end time prices

robot standing at first cell of an M*N matrix. It can move only in two directions, right and down. In how many ways, it can reach to the last cell i.e. (M, N) Code it

Possible sizes of bus to carry n groups of friends

SAP Interview Questions

Given a string, find the first character which is non-repetitive

Flipkart SDET Interview Experience

Knight Tour Problem (Graph – Breadth First Search)

Convert number to words java

Interfaces in C++ (Abstract Classes in C++)

Reverse a Linked List in groups of given size

Copyright © 2025 · Genesis Framework · WordPress · Log in