Given a stack of integers A, sort it using another stack.
Return the array of integers after sorting the stack using another stack.
Problem Constraints
1 <= |A| <= 5000
0 <= A[i] <= 109
Input Format
The only argument is a stack given as an integer array A.
Output Format
Return the array of integers after sorting the stack using another stack.
Example Input
Input 1:
Output 1:
A = [5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
Input 2:
[5, 11, 17, 100]
Explanation 1:
Just sort the given numbers.
Output 2:
A = [5, 17, 100, 11]
Explanation 2:
Just sort the given numbers.
module.exports = {
//param A : array of integers
//return a array of integers
solve: function (input) {
let tmpStack = [];
while (input.length > 0)
{
// pop out the first element
let tmp = input.pop();
// while temporary stack is not empty and
// top of stack is lesser than temp
while (tmpStack.length > 0 && tmpStack[tmpStack.length - 1] < tmp)
{
// pop from temporary stack and
// push it to the input stack
input.push(tmpStack[tmpStack.length - 1]);
tmpStack.pop()
}
// push temp in temporary of stack
tmpStack.push(tmp);
}
return tmpStack.reverse();
}
};