880824. Reverse Array Using Stack

Basic

Reverse Array Using Stack

Summary

Given an array, reverse its elements using a stack data structure. The problem involves manipulating the array by pushing and popping elements from the stack to achieve the desired reversal.

Detailed Explanation

The approach is straightforward: push each element of the array onto the stack, then pop each element off the stack and store it in a new array. This process effectively reverses the original array.

Here's a step-by-step breakdown:

  1. Create an empty stack S.
  2. Iterate through the input array arr from left to right.
  3. For each element x in arr, push x onto the stack S.
  4. After pushing all elements, create an empty output array res.
  5. Pop each element off the stack S and append it to the end of the output array res.
  6. Return the reversed array res.

Time complexity: O(n), where n is the length of the input array. Space complexity: O(n), as we need to store all elements in the stack and the output array.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] reverseArray(int[] arr) {
    Stack<Integer> S = new Stack<>();
    for (int x : arr) {
        S.push(x);
    }
    int[] res = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        res[i] = S.pop();
    }
    return res;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.