Array Basics to Advance
In this article, we’ll look at one of the most fundamental problems in data structures: reversing an array. This is a common interview question and is also a great starting point for beginners learning about arrays and two-pointer techniques.
Problem Statement
We are given an array, and we need to reverse the elements in-place, meaning without using extra space for another array.
Examples:
Input: arr = [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]Input: arr = [4, 5, 2]
Output: [2, 5, 4]✅ Approach 1: Two-Pointer Technique
Get Mayur777’s stories in your inbox
Join Medium for free to get updates from this writer.
We use two pointers:
istarts from the beginning (index 0),jstarts from the end (last index).
We swap the elements at positions i and j and then move the pointers inward (i++ and j--). Repeat the process until i >= j.
void reverseArray(vector<int> &arr) {
int i=0, j= arr.size()-1;
while(i<j){
swap(arr[i],arr[j]);
i++,j — ;
}
}
Time Complexity: O(n)
Space Complexity: O(1)
✅ Approach 2: Using STL (Standard Template Library)
There is an inbuild function where i can reverse all elements in an array
void reverseArray(vector<int> &arr) {
reverse(arr.begin(),arr.end());
}
Time Complexity: O(n)
Space Complexity: O(1)
📌 Link to the Problem
https://www.geeksforgeeks.org/problems/reverse-an-array/1





