Sitemap
Mayur777

Mayur777

🚀 Sharing my journey from basics to advanced coding 🧠 Daily coding questions & solutions | Let's grow together! 📍 Learning, Building & Evolving

Array Basics to Advance

1 min readMay 16, 2025

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:

  • i starts from the beginning (index 0),
  • j starts 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

--

--

Mayur777
Mayur777

Written by Mayur777

🚀 Sharing my journey from basics to advanced coding 🧠 Daily coding questions & solutions | Let's grow together! 📍 Learning, Building & Evolving