# Reverse an array using Stack

## Introduction:

We need to reverse an array of ‘N’ elements using a Stack only. Stack is q linear data structure in which we can add or remove the element from the top of the stack only.

Input 1:

[1, 2, 3, 4, 5]

Output 1:

[5, 4, 3, 2, 1]

## 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:-

1. We will add all the elements of the array one by one to the Stack.
2. Now while removing the elements from the stack we know the element which was added in the last will get removed first.
3. Hence, we will just keep removing the elements from the stack and keep adding those elements to our array from the starting.
4. After removing all the elements from the stack, we can see that our array will get reversed.

Refer to the below implementation of the above approach.

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.

## FAQs:

1. What are 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.
2. 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.

## Key Takeaways:

In this blog, we have covered the following things:

1. We first discussed the Stack approach to solve this problem.
2. Then we discussed the time and space complexity of the approach used.

If you want to learn more about Stack and want to practice some questions which require you to take your basic knowledge on Stack a notch higher, then you can visit our Guided Path for Stack. To practice this problem, you can visit Practice Problem.

Until then, All the best for your future endeavors, and Keep Coding.  