Sort and Reverse stack with recursion

Problem description:
Sort a stack
Difficulty: MediumAccuracy: 69.19%Submissions: 132K+Points: 4
Given a stack, the task is to sort it such that the top of the stack has the greatest element.

Example 1:

Input:
Stack: 3 2 1
Output: 3 2 1
Example 2:

Input:
Stack: 11 2 32 3 41
Output: 41 32 11 3 2
Your Task:
You don't have to read input or print anything. Your task is to complete the function sort() which sorts the elements present in the given stack. (The sorted stack is printed by the driver's code by popping the elements of the stack.)

Expected Time Complexity: O(N*N)
Expected Auxilliary Space: O(N) recursive.

Constraints:
1<=N<=100

class Main {
    public static void insertInStackByOrder(Stack<Integer> s,int elem){
        if(s.isEmpty() || s.peek()<=elem){
            s.push(elem);
            return;
        }
        
        int temp = s.pop();
        insertInStackByOrder(s,elem);
        
        s.push(temp);
        
    }
    public static void helper(Stack<Integer> s){
        if(s.isEmpty()){
            return;
        }
        int elem = s.pop();
        helper(s);
        
        insertInStackByOrder(s,elem);
    }
    public Stack<Integer> sort(Stack<Integer> s) {
        helper(s);
        return s;
    }
}

Reverse a Stack
Difficulty: MediumAccuracy: 80.5%Submissions: 92K+Points: 4
You are given a stack St. You have to reverse the stack using recursion.

Example 1:

Input:
St = {3,2,1,7,6}
Output:
{6,7,1,2,3}
Explanation:
Input stack after reversing will look like the stack in the output.
Example 2:

Input:
St = {4,3,9,6}
Output:
{6,9,3,4}
Explanation:
Input stack after reversing will look like the stack in the output.
Your Task:

You don't need to read input or print anything. Your task is to complete the function Reverse() which takes the stack St as input and reverses the given stack.

Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(1)

Constraints:
1 <= size of the stack <= 104
-109 <= Each element of the stack <= 109
Sum of N over all test cases doesn't exceeds 106
Array may contain duplicate elements.

class Solution
{ 
    public static void insertInStackByOrder(Stack<Integer> s,int elem){
        if(s.isEmpty()){
            s.push(elem);
            return;
        }
        
        int temp = s.pop();
        insertInStackByOrder(s,elem);
        
        s.push(temp);
        
    }
    public static void helper(Stack<Integer> s){
        if(s.isEmpty()){
            return;
        }
        int elem = s.pop();
        helper(s);
        
        insertInStackByOrder(s,elem);
    }
    static void reverse(Stack<Integer> s)
    {
        helper(s);
    }
}
Comments (4)