Reverse an Array in C++ — Efficient Array Reversal Algorithm
Learn how to reverse an array in C++ using a simple algorithm. This post covers reversing an array with code, edge cases.
Problem: Reverse an Array

You are given an array of integers arr . Your task is to reverse the given array and return the reversed array.
Problem Statement:
Given an array arr, write a function to reverse the elements of the array. The function should return a new array that contains the elements of arr in reverse order.
Example
Example 1:
- Input:
arr = [1, 2, 3, 4, 5] - Output:
[5, 4, 3, 2, 1] - Explanation: The array
[1, 2, 3, 4, 5]is reversed to[5, 4, 3, 2, 1].
Example 2:
- Input:
arr = [9, 8, 7] - Output:
[7, 8, 9] - Explanation: The array
[9, 8, 7]is reversed to[7, 8, 9].
Approach
- Initialization:
First, get the size of the input array
arrand create a new arrayrevarrof the same size to store the reversed elements. - Reverse Using a Loop:
Use a loop to iterate through the input array from the beginning to the end. In each iteration, assign the element from the end of
arrto the corresponding position inrevarr. - Return the Reversed Array:
Once all elements have been copied in reverse order, return the
revarrarray.
Solution Code (C++)
class Solution {
public:
vector<int> reverseArray(vector<int> &arr) {
int size = arr.size(); // Get the size of the array
vector<int> revarr(size); // Create a new array of the same size
// Loop to reverse the array
for (int i = 0; i < size; i++) {
revarr[i] = arr[size - 1 - i]; // Assign elements from the end of arr
}
return revarr; // Return the reversed array
}
};
Explanation
- Array Size:
The size of the input array is determined using
arr.size(). - Reversing Elements:
The loop starts from index
0and runs until the end of the array. For each indexi, the corresponding element from the end ofarris copied torevarr[i]. - Final Output:
After the loop completes, the reversed array
revarris returned.
Time and Space Complexity
- Time Complexity:
The time complexity is
O(n)wherenis the number of elements in the array, because each element is accessed and copied exactly once. - Space Complexity:
The space complexity is
O(n)because we create a new arrayrevarrto store the reversed elements.
Edge Cases
- Empty Array: If the input array is empty, the function will return an empty array without entering the loop.
- Single Element Array: If the input array has only one element, the function will return the same array, since reversing a single-element array doesn’t change its order.
메타데이터
- post_id
- 56f014d072ae
- slug
- reverse-an-array-in-c-efficient-array-reversal-algorithm-56f014d072ae
- url
- https://medium.com/@gauravssah/reverse-an-array-in-c-efficient-array-reversal-algorithm-56f014d072ae
- canonical_url
- https://medium.com/@gauravssah/reverse-an-array-in-c-efficient-array-reversal-algorithm-56f014d072ae
- author_url
- https://medium.com/@gauravssah
- status
- ok
- fetched_at
- 2026-07-21 03:40:02