This is a question that I was asked for during a job interview.

Sort a stack using a temporary stack.

I have made a video explaining the solution here https://www.youtube.com/watch?v=ocFJyyL3Yfc&t=78s

The code is in Typescript. I am actually using an array instead of a stack. But, I am accessing only the top element of the array. I have no time to implement an actual stack data structure. This will likely be acceptable in an actual interview.

1
2
3
4
5
6
7
8
9
10
11
12
13
function sortStack(ip: number[]): number[]{
const temp: number[] = [];
while(ip.length>0){
const t = <number>ip.pop();
while(t<temp[temp.length-1]){
ip.push(<number>temp.pop());
}
temp.push(t);
}
return temp;
}
console.log(sortStack([1,3,2]));
console.log(sortStack([5,4,3,2,1]));

To run this code:
tsc filename.ts
npx filename.js