#include <iostream> #include <iomanip> #include <stack> #include <conio.h> /* Push() and Pop() methods of stack are given. Write a function to get the minimum of stack in O(1) time - can be done by maintaining the following invariant in all the operations in the stack "The top element of the stack is always the smallest number" - an auxillary stack is used to maintain this invariant during push operations */ std::stack<int> stack; /* - check if x < stack.top() - if yes, push it in - if no, - pop all the elements from the stack till we get x < stack.top() and push into aux stack - push x - push all the elements from aux stack back to main stack - This maintains above stated invariant */ void push(int x) { std::stack<int> aux; // using loop and a half idiom ... while(true && stack.size() > 0) { if(stack.top() > x) break; else { aux.push(stack.top()); stack.pop(); } } // now we have two stacks, stack with all elements > x and aux with // all elements < x stack.push(x); while(aux.size() > 0) { stack.push(aux.top()); aux.pop(); } } int main() { push(3); push(1); push(2); push(6); push(4); push(12); push(10); push(8); // some tests assert(stack.top() == 1); stack.pop(); assert(stack.top() == 2); stack.pop(); assert(stack.top() == 3); getch(); }
Yet another blog from yet another software engineer - a collection of my thoughts and some snippets of code I write (mainly for my later reference). If you find this useful, lets discuss in comments.
December 18, 2012
Minimum of stack in O(1)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment