Google Interview Question
1,071 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer Intern at Google:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (7)
0 of 1 people found this helpful
Stack S1; //stack contains data of ints
int Stack::getmin(Stack& S1)
{
int min=1000000; //initialize min
Stack S2;
//Transfer all from S1 to S2
while(!S1.isEmpty())
{
int temp = S1.pop();
if (temp<min)
{
min = temp; //set minimum
}
S2.push(temp); //put items in S2
}//end while
//Transfer all from S2 back to S1
while(!S2.isEmpty())
{
S1.push(S2.pop());
}
return min;
}//end getmin
Helpful Answer?
Yes |
No
Inappropriate?
0 of 1 people found this helpful
int min=firstInt;
if(min>=nextPush)
min=nextPush;
Really you could just make that into a separate method too and just call it with push . . . or maybe I'm over simplifying.
Helpful Answer?
Yes |
No
Inappropriate?
It's not that simple. Say you pushed 1, 2, and 3, and then popped 1. If you just keep track of the minimum that was pushed, you would still have 1 but that's not even in the stack anymore.
You also can't just erase the value if you pop it off, because then a situation that was like push 1, 1, 2, 3, pop 1 would give you the wrong answer (i.e. should still be 1).
Helpful Answer?
Yes |
No
Inappropriate?
class gmStack{
private
Stack<item> S;
Stack<item> m;
public
gmStack();
~gmStack();
void push(item *);
item * pop();
item * getMin();
}
void gmStack::push(item * i){
S.push(i);
item *t=m.pop(); m.push(t);
if(i<=t) m.push(i);
}
item *gmStack::pop(){
item *t=m.pop();
item *r=S.pop();
if(t!=r) m.push(t);
return r;
}
item *gmStack::getMin(){
item *t=m.pop(); m.push(t);
return t;
}
gmStack::gmStack(){
S=new Stack();
m=new Stack();
}
gmStack::~gmStack(){
delete S;
delete m;
}
Helpful Answer?
Yes |
No
Inappropriate?
Members can
answer or comment on this question
–
Join Now (It's Free) or
Sign In
0 of 1 people found this helpful
by Interview Candidate: