DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Two Pointer for Beginners — Reverse an Array (In-Place)

When starting with the Two Pointer technique, one of the simplest and most important problems is reversing an array without using extra space.

This problem builds the foundation for many advanced two-pointer problems.

🧩 Problem: Reverse an Array

Description

You are given an array.
Reverse the elements in the same array (no new array allowed).

Example 1

Input:  [1, 2, 3, 4]
Output: [4, 3, 2, 1]

Enter fullscreen mode Exit fullscreen mode

Example 2

Input:  [5, 10, 15]
Output: [15, 10, 5]

Enter fullscreen mode Exit fullscreen mode

🧠 Why Two Pointer?

If we try to reverse using loops and extra arrays, we waste memory.With Two Pointer (Opposite Direction):

  • We reverse in-place
  • Time Complexity → O(n)
  • Space Complexity → O(1)
  • Perfect for beginners 🚀

✍️ Simple Approach (English Explanation)

Step 1

  1. Use two pointers
  2. left at the beginning of the array
  3. right at the end of the array

Step 2

  1. Swap the elements at left and right

Step 3

  1. Move the pointers
  2. left++
  3. right--

Step 4

  1. Repeat until left < right

❗ Important

We stop when left >= right, because:

In odd length arrays → pointers meet at the middle
In even length arrays → pointers cross

🔄 Visual Pointer Movement

Initial:

[1, 2, 3, 4]
 L        R

Enter fullscreen mode Exit fullscreen mode

After 1st swap:

[4, 2, 3, 1]
    L  R

Enter fullscreen mode Exit fullscreen mode

After 2nd swap:

[4, 3, 2, 1]

Enter fullscreen mode Exit fullscreen mode

Done ✅

💻 Convert Simple Approach to Code (C++)

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4};
    int n = sizeof(arr) / sizeof(arr[0]);

    int left = 0;
    int right = n - 1;

    while (left < right) {
        swap(arr[left], arr[right]);
        left++;
        right--;
    }

    // Print reversed array
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

⏱️ Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1) (in-place)

🎯 Key Takeaway

This problem teaches the core rule of Two Pointer (Opposite Direction):

If two elements need to be swapped or compared symmetrically,
use left and right pointers and move them toward each other.

Once this clicks, problems like:

Palindrome check
Two Sum (sorted)
Container With Most Water
become much easier.

🌱 What to Practice Next?

Reverse a string
Valid Palindrome
Remove duplicates from sorted array
Move zeros

Top comments (0)