VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-middle-element-stack/

⇱ Delete Middle of a Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete Middle of a Stack

Last Updated : 14 Mar, 2026

Given a stack s, remove the middle element of it without using any additional data structure.

Input: s = [10, 20, 30, 40, 50]
Output: s = [10, 20, 40, 50]
Explanation: After deleting the mid which is 30, stack will look like [10, 20, 40, 50].

Input: s = [1, 2, 3, 4]
Output: s = [1, 3, 4]
Explanation: The stack has 10 elements (even), there are two mid elements 2 and 3, we delete the first of the two.

Note : The output printed by the following codes is reverse of the order as we pop the top elements one by one and print.

Using Vector - O(n) Time and O(n) Space

  • Create a vector to store stack elements.
  • Pop all elements from the stack and store them in the vector.
  • Identify the middle element index: n/2 for even n, ceil(n/2) for odd n (0-based indexing).
  • Skip the middle element and push the remaining elements back to the stack in reverse order.

Output
50 40 20 10 

Using Recursion - O(n) Time and O(n) Space

  • Store the stack size (n) and initialize a counter (current) to track popped elements.
  • Recursively, Pop an element and increment current and If current == n/2, pop the middle element and stop recursion. Otherwise, continue recursion.
  • Push back the popped element after the recursive call.

Output
50 40 20 10 

Using Temporary Stack - O(n) Time and O(n) Space

  • Initialize a temporary stack and a counter (count).
  • While count < n/2, pop elements from the original stack and push to the temporary stack.
  • Pop the middle element from the original stack.
  • While the temporary stack is not empty, pop elements from it and push to the original stack.

Output
50 40 20 10 
Comment
Article Tags: