![]() |
VOOZH | about |
Reverse an array arr[]. Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes second last and so on.
Examples:
Input: arr[] = [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]
Explanation: The first element 1 moves to last position, the second element 4 moves to second-last and so on.Input: arr[] = [4, 5, 1, 2]
Output: [2, 1, 5, 4]
Explanation: The first element 4 moves to last position, the second element 5 moves to second last and so on.
Table of Content
The idea is to use a temporary array to store the reverse of the array.
- Create a temporary array of same size as the original array.
- Now, copy all elements from original array to the temporary array in reverse order.
- Finally, copy all the elements from temporary array back to the original array.
Working:
5 6 2 3 4 1
Time Complexity: O(n), Copying elements to a new array is a linear operation.
Auxiliary Space: O(n), as we are using an extra array to store the reversed array.
The idea is to maintain two pointers: left and right, such that left points at the beginning of the array and right points to the end of the array.
While left pointer is less than the right pointer, swap the elements at these two positions. After each swap, increment the left pointer and decrement the right pointer to move towards the center of array. This will swap all the elements in the first half with their corresponding element in the second half.
Working:
5 6 2 3 4 1
The idea is to iterate over the first half of the array and swap each element with its corresponding element from the end. So, while iterating over the first half, any element at index i is swapped with the element at index (n - i - 1).
Working:
5 6 2 3 4 1
Time Complexity: O(n), the loop runs through half of the array, so it's linear with respect to the array size.
Auxiliary Space: O(1), no extra space is required, therefore we are reversing the array in-place.
The idea is to use inbuilt reverse methods available across different languages.
5 6 2 3 4 1
Time Complexity: O(n), the reverse method has linear time complexity.
Auxiliary Space: O(1) Additional space is not used to store the reversed array, as the in-built array method swaps the values in-place.