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:
- Create an empty stack
S. - Iterate through the input array
arrfrom left to right. - For each element
xinarr, pushxonto the stackS. - After pushing all elements, create an empty output array
res. - Pop each element off the stack
Sand append it to the end of the output arrayres. - 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
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;
}