Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Sort a stack

Medium Acceptance 69.19% Points 30.00

The task is to sort a stack so that the top of the stack has the greatest element. You need to complete the function sort() which sorts the elements present in the given stack.

Examples
Example 1

Example 1

Input: Stack: 7 5 9 2 4

Output: 9 7 5 4 2

Explanation: The stack is sorted in descending order where 9 is the topmost element, followed by 7, 5, 4, and 2 at the bottom.

Example 2

Example 2

Input: Stack: 13 19 5 8 1

Output: 19 13 8 5 1

Explanation: The stack is sorted such that the greatest element, 19, is at the top, followed by 13, 8, 5, and 1 at the bottom.

Hints
Hint 1
Expected Time Complexity: O(N*N)
Hint 2
Expected Auxilliary Space: O(N) recursive.
Constraints
  • 1<=N<=100
Companies
Amazon Microsoft Goldman Sachs IBM Intuit + 1 more
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions