I was recently asked this interview question:
How to retrieve the first 5 items in the stack ?
Stack as you know is Last In First Out
Interviewer asked for algorithm/pseudocode with high performance for a stack with only 2 operations, Pop() and Push().
My trivial answer:
Stack S2;
foreach (item in stack S1)
{
object item = S1.Pop();
S2.push(item)
}
for (int i=0 ; i<5 ; i++)
Printf(S2.Pop());
He told me that we have another solution with higher performance but I cannot find one.
Seems to have been a communication issue. To get the first five elements that were put onto the stack then I would do the following:
End Result: