Approach
As we all know, that stack follows the property of Last In First Out (L.I.F.O.). We will make use of this property to reverse an array.
We will follow the following steps:-
- We will add all the elements of the array one by one to the Stack.
- Now while removing the elements from the stack we know the element which was added in the last will get removed first.
- Hence, we will just keep removing the elements from the stack and keep adding those elements to our array from the starting.
- After removing all the elements from the stack, we can see that our array will get reversed.
Recommended Topic: Recursion
Refer to the below implementation of the above approach.
public static int[] reverse(int arr[]){
int n = arr.length;
// Initialize a stack of capacity n
Stack stack = new Stack(n);
for (int i = 0; i < n; i++) {
// Inserting arr[i] values to the stack
stack.push(arr[i]);
}
// Reverse an array elements
for (int i = 0; i < n; i++) {
// Updating the arr[i] values
arr[i] = stack.pop();
}
return arr;
}

You can also try this code with Online Java Compiler
Run Code
Time Complexity: The time complexity of the above approach is O(N) (where N is the length of the String) because we are iterating the array twice.
Space Complexity: The space complexity for the above approach is O(N) because we are maintaining a Stack that will store all the elements of the array.
Must Read C Program to Reverse a Number
Frequently Asked Questions
What is the Time and Space complexity of the approach used to reverse an array?
Time Complexity: The time complexity of the approach used to reverse an array is O(N) (where N is the length of the String) because we are iterating the array twice.
Space Complexity: The space complexity for the approach used to reverse an array is O(N) because we are maintaining a Stack that will store all the elements of the array.
Which property of stack helped us to reverse an array?
The Last In First Out(L.I.F.O.) property of the stack helped us to reverse an array.
Conclusion
In this blog, we have covered the following things:
- We first discussed the Stack approach to solve this problem.
-
Then we discussed the time and space complexity of the approach used.
Recommended Reading:
Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, DBMS, System Design, Basics of JavaScript, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio. You can also consider our Mern Stack Course to give your career an edge over others.
Cheers!