## Bloomberg LP Interview Question

Financial Software Developers**Country:**United States

**Interview Type:**Phone Interview

That works great as long as you are pushing new elements in the stack. But if you had to pop something out, this will lead you into trouble.

Popping will not lead you into trouble. Example: We add:

9 -> min 9

13 -> min 9

5 -> min 5

10 -> min 5

2 -> min 2

30 -> min 2

We pop:

30 -> min still 2

2 -> min is 5

10 -> min is 5

5 -> min is 9

13 -> min is 9

9 -> empty stack

What I said above is true if you use stack nodes with 2 fields: value and min. That's what I understood from running's solution. I think you interpreted it as a single separate variable - min.

import java.util.ArrayList;

import java.util.Collections;

import java.util.Stack;

public class C {

public static void main(String[] args) {

Stack<Integer> st = new Stack<Integer>();

ArrayList<Integer> list = new ArrayList<Integer>();

st.push(12);

st.push(15);

st.push(6);

st.push(2);

st.push(23);

st.push(18);

while(!(st.isEmpty())){

int top = st.pop();

list.add(top);

}

System.out.println(list);

Collections.sort(list);

System.out.println(list.get(0));

}

}

Few problems with this

1) you are emptying the stack to find the min/max....in turn destroying your data

2) The moment you empty the stack to make a list, your constrain of being Constant time is gone for a toss. You will spend as much time as the number of elements. Similarly, sorting will require O(N lgN) time

Maintain a minimum stack.

Push call is required you perform two operations:

1. push(a) on your stack

2. push(a) on min-stack if the min-stack-top > a

Pop call is required you to perform the following:

1. pop() on you stack

2. pop() on min-stack of the popped element is the min-stack-top.

```
public class minInStack {
int[] stack = new int[20];
int top = -1;
public void push(int element){
top++;
stack[top] = element;
}
public int pop (){
return stack[top--];
}
public static void main(String[] args) {
minInStack obj = new minInStack();
int[] ip = {10,2,4,5,6,7,8,9}; // Sample input to stack
int i=0,min = 0,pop;
for ( ; i< ip.length;i++){
obj.push(ip[i]);
}
min = obj.pop();
for (i = 1;i<ip.length-1;i++){
pop = obj.pop();
if(pop < min)
min = pop;
}
System.out.println("Minimum Element in Stack: "+min);
}
}
```

One simple way would be to have a variable that maintains the min value.

- running July 03, 2013