Calculate (not design!) the minimum of a stack in Java
<p>I want to write a function to <strong>calculate</strong> (not design) the minimum of a given stack. I thought that I can find that easily in the net but I found <em>nothing</em> about that. All what I found is to how to design a stack with a getMinimum function.</p>

<p>The difference is that when you design such a stack, you will gradually construct your stack (push and pop) and updating the minimum value after any operation. I was thinking, how if you have a given stack and you want to calculate the minimum of this stack, how can you deal with that? Perhaps, I don't reason very well or I'm asking myself the wrong answers or I don't understand very well the concept of the stack but it surprise me to don't find any answer about that in the net, even after a lot of search...</p>

<p>Here is my attempt : </p>

<pre><code>    public static int min(Stack stack){
        Stack temp = new Stack();
        int result = Integer.MAX_VALUE;
        while(!stack.isEmpty()) {
                int value = stack.pop();
                temp.push(value);
                result =  (result &gt;= value)? value : result;
            }
    //stack is empty now, I have to recuperate it from the temp stack
             while(!temp.isEmpty()) {
                     stack.push(temp.pop());
             }

             return result;
      }
</code></pre>

<p>In this code, I use my own implementation for Stack and Node. But as you can see, the code is very simple. I wrote this post mainly because I'm asking myself a lot of questions about that. </p>

<p>Especially, I want to ask you please three main questions :</p>

<ul>
<li>What is the time and the space complexity for this function? I think it's O(N), is it right? I always get some difficulties to calculate that in my program. It's normally O(2*N) (which equals O(N) ) since we run through the stack node per node. </li>
<li>Is my approach logical or not? From what I understand, if you want to get acces to the kth element in a stack, you have to pop the k-1 previous element. Or here, in my opinion, it's absolutely not logical to pop an entire stack if we just want to calulate its minimum (if you want to manipulate again the same stack). It's why I did a second while loop to keep the stack in its original state.</li>
<li>Perhaps, we can made a copy of the stack, but I read that cloning objects in Java is no that easy and I'm wondering if it will not be very consuming for a little function like this?</li>
</ul>

<p>Thanks</p>