![]() |
VOOZH | about |
Given a stack S and an integer K, the task is to reverse the first K elements of the given stack
Examples:
Input: S = [ 1, 2, 3, 4, 5, 8, 3, 0, 9 ], K = 4
Output: [ 4, 3, 2, 1, 5, 8, 3, 0, 9 ]
Explanation: First 4 elements of the given stack are reversed
Input: S = [ 1, 2, 3, 4, 5, 8, 3, 0, 9 ], K = 7
Output: [ 3, 8, 5, 4, 3, 2, 1, 0, 9 ]
Approach: The task can be solved using two auxiliary stacks to reverse the first K elements of the given stack. Follow the below steps to solve the problem:
Below is the implementation of the above approach:
4 3 2 1 5 8 3 0 9
Time Complexity: O(N), N is the number of elements in the stack
Auxiliary Space: O(N)