Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Data Structure for push, pop and finding minimum

I was just asked an interview question with company A as follows:

Question : Design a data structure in which you have 3 operations, push, pop and find the minimum. You should be doing all the 3 operations in constant time.

My Answer : I would use a linked list in which i can do insertion and removal in constant time and i would use an extra memory to store the minimum.

He came up with a second question saying, if you pop the minimum, how do you find the second minimum? again, in constant time.

What would you tell him?

like image 569
DarthVader Avatar asked May 23 '11 21:05

DarthVader


People also ask

Which data structure uses push and pop?

In computer science, a stack is an abstract data type that serves as a collection of elements, with two main operations: Push, which adds an element to the collection, and. Pop, which removes the most recently added element that was not yet removed.

How do you find the minimum value in a stack?

To find the minimum element, just look at the top of the minimums stack. Pushing, popping and finding the min value are O(1).

Which data structure is best for insertion and deletion?

A linked list provides efficient insertion and deletion of arbitrary elements.

How do you pop in data structure?

Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.


1 Answers

Minimum stack question - http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_A.pdf

From the PDF:

Question: Minimum Stack

Describe a stack data structure that supports "push", "pop", and "find minimum" operations. "Find minimum" returns the smallest element in the stack.

Good Answer: Store two stacks, one of which contains all of the items in the stack and one of which is a stack of minima. To push an element, push it onto the first stack. Check whether it is smaller than the top item on the second stack; if so, push it onto the second stack. To pop an item, pop it from the first stack. If it is the top element of the second stack, pop it from the second stack. To find the minimum element, simply return the element on the top of the second stack. Each operation takes O(1) time.

like image 58
Ryan Reeves Avatar answered Sep 21 '22 23:09

Ryan Reeves