Sort a Stack using Recursion

Get a Strong Hold DSA practice problem on Onlearn.

Difficulty: medium.

Topics: How to sort a stack using recursion?, Recursion, Stack, Sorting, stack operations, recursion, sorting algorithms, stack, Stack Operations.

Sort a Stack Recursively Problem Statement Given a stack of integers, sort it in ascending order such that the smallest elements are at the top of the stack. You are only allowed to use the following standard stack operations: push, pop, top, and is empty. Input Specification The input will be a stack of integers. Output Specification The output should be the same stack, but with its elements sorted in ascending order (smallest element at the top). Constraints The number of elements in the stack N will be between 0 and 1000. Each element in the stack will be an integer between 10^9 and 10^9. Sample Test Cases Sample Input 1: Stack: [3, 1, 4, 2] (top is 2) Expected Output 1: Stack: [1, 2, 3, 4] (top is 1) Explanation: The original stack [3, 1, 4, 2] is sorted to [1, 2, 3, 4] with 1 at the top. Sample Input 2: Stack: [5] (top is 5) Expected Output 2: Stack: [5] (top is 5) Explanation: A stack with a single element is already sorted. Sample Input 3: Stack: [] (empty stack) Expected Output 3: Stack: [] (empty stack) Explanation: An empty stack remains empty.