Sort a Stack

Given a stack represented by an array of integers (with the top of the stack at the end of the array), sort the stack in ascending order so that the smallest elements are on top of the stack. Return the sorted stack as an array.

Input Format

nums = elements of stack (last element is top)

Output Format

sorted stack as array (with smallest elements at top)

Constraints

Examples

Example 1:

Input:

nums = [3,1,4,2]

Output:

[4,3,2,1]

Explanation:

Sorted stack with smallest elements on top (end of array).

Example 2:

Input:

nums = [5,1,2,4,3]

Output:

[5,4,3,2,1]

Explanation:

Sorted stack in ascending order.

Loading...
Sort a Stack - Stack DSA Problem