880820. Delete Mid of a Stack

Easy

Delete Mid of a Stack

Summary

Delete mid of a stack problem involves deleting the middle element from a stack. The stack is represented as an array and elements are accessed in a last-in-first-out (LIFO) order.

Detailed Explanation

To solve this problem, we can use recursion to delete the middle element. Here's a step-by-step breakdown of the solution:

  1. Calculate the middle index of the stack by taking the length of the stack and dividing it by 2.
  2. If the calculated index is out of bounds (i.e., less than 0 or greater than or equal to the length of the stack), return an error message or a special value indicating that there is no middle element.
  3. Delete the element at the calculated index from the stack array.
  4. Return the updated stack array.

Here's an example:

Stack: [1, 2, 3, 4, 5]
Middle Index: (length / 2) = 2
Delete Element at Index 2: [1, 2, 4, 5]
Updated Stack: [1, 2, 4, 5]

The time complexity of this solution is O(1), as we only need to calculate the middle index and delete an element. The space complexity is also O(1), as we are not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public static int[] deleteMid(int[] stack) {
    int n = stack.length;
    if (n <= 0) return new int[0];
    int midIndex = n / 2;
    if (midIndex < 0 || midIndex >= n) return stack; // no middle element
    int[] updatedStack = Arrays.copyOf(stack, n - 1);
    System.arraycopy(updatedStack, midIndex + 1, updatedStack, midIndex, n - midIndex - 1);
    return updatedStack;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.