Reversing an array involves re-arranging the order of all its elements such that the first element becomes the last, the second element becomes the second last element, and so on. For example:
Array Before Reversal:
[ A | B | C | D | E ]
Array After Reversal:
[ E | D | C | B | A ]
Techniques for Reversing an Array
Let’s dive into few common techniques used for reversing arrays:
Iterative Approach Using Extra Space
This method is straightforward but is less memory-efficient due to creation of a new array.
Algorithm:
- Create a temporary array with same size as the original.
- Traverse the original array from end to start and copy the elements into the new array from start to the end.
- Finally, replace the original array with the new reversed array.
Time Complexity: O(N) - The loop iterates through all N elements of the original array once.
Space Complexity: O(N) - A temporary array of size N is created to store the reversed elements.
Iterative In-Place Approach (Two-Pointer Technique)
In-place approach involves using two-pointer technique to efficiently reverse all elements in the Array without using any extra space.
Algorithm:
- Initialize two pointers,
leftpointing to the beginning of the array andrightpointing to the last element. - Swap the elements present at the
leftandrightpositions. - Increment the
leftpointer and decrement therightpointer. - Continue performing the last two steps until the
leftandrightpointers meet or cross each other.
Time Complexity: O(N) - The loop iterates a maximum of N/2 times (from start to middle) as elements are swapped in pairs.
Space Complexity: O(1) - The algorithm uses constant extra space for the two pointers (left and right).
Recursive In-Place Approach
The recursive approach also modifies the array in-place, but it does so by breaking the problem down into smaller subproblems. While elegant, it is not the most space-efficient solution for large arrays due to recursion’s stack space overhead.
Algorithm:
- Define a function that takes the array,
left, andrightindices as arguments. - Base case: If
leftis greater than or equal toright, it means that the array is reversed already reversed. - Otherwise, swap the elements at
leftandright. - Recursively call the function with
left + 1andright - 1.
Time Complexity: O(N) - Function is recursively called for N/2 times
Space Complexity: O(N) - Due to stack space consumed by N/2 recursive function calls.
Built-in Functions (if applicable)
Learning all previous approach helps in understanding the different algorithms which could be used as building blocks for more complicated use-cases. But if you just need to reverse an array, many programming languages offer built-in functions or methods to reverse arrays which can be conveniently used to reverse arrays with just a single line of code.