Min Stack
July 27, 2012
Today’s exercise continues our occasional series of exercises based on interview questions:
Design a data structure that provides push and pop operations, like a stack, plus a third operation that finds the minimum element. All three operations must perform in constant time. You may assume that all elements are distinct.
Your task is to write the three indicated functions. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
[…] today’s Programming Praxis exercise, our goal is to create s stack-like data structure that can push, pop […]
My Haskell solution (see http://bonsaicode.wordpress.com/2012/07/27/programming-praxis-min-stack/ for a version with comments):
Javascript. I used a function constructor.
Python version:
For the push operation, I think you need to add the new item to the min stack if it is returns 0, but also clears a 0 from the minimum stack
minimum –> should still be zero
Sorry, a less than symbol messed up my comment.
I think the push operation needs to add the new item to the minimum stack when it is less than or equal to the current minimum. Otherwise, a minimum item could get popped off to soon. Consider this sequence of operations:
The problem text states that all items are distinct.
Mike, pushing 3 onto the stack twice is actually not legal according the specification: “You may assume that all elements are distinct”.
Clojure solution almost similar to the Haskell one
Alternate solution, using protocol and an helper constructor
Whatever the solution you can use it the same way
A Go solution similar to the Python one:
Learning a bit of c++:
#ifndef CSTACK_H
#define CSTACK_H
using namespace std;
struct node {
int x;
node *next;
};
class CStack {
public:
CStack();
CStack(const CStack& orig);
virtual ~CStack();
void push(int x);
int pop();
int minimum();
private:
int min;
node *head;
};
#endif /* CSTACK_H */
#include “CStack.h”
#include
#include
using namespace std;
CStack::CStack() {
min=1000;
}
CStack::CStack(const CStack& orig) {
}
CStack::~CStack() {
}
int CStack::minimum() {
return min;
}
void CStack::push(int x) {
node *current;
if(head != NULL){
current = new node;
current->x=x;
if(min>x){
min=x;
}
current->next=head;
head=current;
}
else{
head = new node;
min=x;
head->x=x;
}
}
int CStack::pop() {
int ret = head->x;
head=head->next;
return ret;
}
[…] Pages: 1 2 […]
Perl6 version:
[…] problem: Min Stack Design a data structure that provides push and pop operations, like a stack, plus a third operation […]
should rename the method name as http://swuecho.wordpress.com/2012/08/04/min-stack/, because of names conflict.