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?
What if you do a linked list, like you said, but also store the current minimum value. When you add a new number it looks at the previous min and changes the current min to the current value if the current value is lower.
E.g… Assume you have the data: 3, 6, 4, 2, 7, 1. Then this is what the list would look like
value|min
3|3 -> 6|3 -> 4|3 -> 2|2 -> 7|2 -> 1|1
That’ll keep track of the mins as you add/remove items.
EDIT:
I mentioned going backwards, it would be something like this:
1|1 -> 7|2 -> 2|2 -> 4|3 -> 6|3 -> 3|3
Then you wouln’t need the “footer”.