VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-first-k-elements-of-the-given-stack/

⇱ Reverse first K elements of the given Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse first K elements of the given Stack

Last Updated : 23 Jul, 2025

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:

  • Create two stacks s1 and s2
  • One by one pop all elements of the given stack and simultaneously push it into stack s1
  • Now, pop k number of elements from s1 and push it in s2 simultaneously
  • Pop all elements from stack s2, and push them into the given stack
  • Similarly pop all elements from s1, and push them into the given stack

Below is the implementation of the above approach:


Output
 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) 


 

Comment
Article Tags:
Article Tags: