I need to find the minimum in a stack using constant time O(1).
So for example, my current stack contains elements: 20 7 10 5 15
I need to find the minimum, pop the stack, and re-find the minimum.
An example output:
Current min in stack: 5
Popped: 15
Current min in stack: 5
Popped: 5
Current min in stack: 7, since its the next lowest ele
Popped: 10
current min in stack: 7
I do not understand how this can be achieved using a constant runtime.
Also another question, what is the run time for a do-while loop? logn?
At this time I don't know how to answer your question - I don't even think there is and answer, but I am not so sure.
But, I can answer your second question:
alex067 wrote:
what is the run time for a do-while loop? logn?
It depends. No matter what looping structure you use - be it for, while, do-while, recursion, goto, etc. - you have to calculate the time complexity the same way. It depends.
Hm, ok well so far I have this code which finds the min whilst pushing elements to the stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
stack<int> myS;
stack<int> minS;
int ele;
int size = 0;
int min = 100;
cout << "Pushing 5 elements into the stack... " << endl;
do
{
cin >> ele;
myS.push(ele);
size++;
if (myS.top() < min)
{
min = ele;
}
} while (size != 5);
Your code finds the min of all the elements in the stack and has the same timing as the special stack thing. But yours will suffer in terms of time when you pop an element and now try to determine the minimum.
There is an easy way to fix this by making use of that minS stack you have in your code which will now make everything O(1) - pop, push, min http://cpp.sh/3ehh