Problem Statement
Given an array of size n
, write a function to reverse the elements of the array. The task is to reverse the array in-place, which means you should not use extra space for another array.
Examples
Example 1:
Input: arr = [1, 2, 3, 4, 5]
Output: arr = [5, 4, 3, 2, 1]
Example 2:
Input: arr = [1, 2, 1, 3]
Output: arr = [3, 1, 2, 1]
Different Approaches
1️⃣ Recursive Approach
#include<iostream>
using namespace std;
// Function to reverse the array using recursion
void reverseArrayRecursively(int arr[], int left, int right) {
if (left >= right) {
return; // Base case: when left and right pointers meet
}
// Swap the elements
swap(arr[left], arr[right]);
// Recursively call the function for the next set of elements
reverseArrayRecursively(arr, left + 1, right - 1);
}
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
reverseArrayRecursively(arr, 0, n - 1);
cout << "Reversed array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Complexity Analysis:
- Time Complexity:
O(n)
- Each recursive call processes two elements (one from the start and one from the end of the array).
- The total number of recursive calls is n/2 since every recursive call works on two elements.
- However, even though there are
n/2
recursive calls, we still look atn
elements in total. In Big-O notation, constants are ignored, so the overall time complexity is still:O(n)
.
- Space Complexity:
O(n)
- Each recursive call adds a frame to the call stack. Since there are n/2n/2n/2 recursive calls, the space complexity for the recursion stack grows in proportion to the number of recursive calls.
- There are n/2 recursive calls, each of which requires a stack frame.
- Thus, the space complexity is
O(n/2)
- However, in Big-O notation, constants like
1/2
are ignored, so the space complexity is considered:O(n)
.
- Each recursive call adds a frame to the call stack. Since there are n/2n/2n/2 recursive calls, the space complexity for the recursion stack grows in proportion to the number of recursive calls.