Reverse an array using Stack

Nishant Rana
Last Updated: May 13, 2022

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.

 

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;
}

 

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.








 

Was this article helpful ?
0 upvotes