DEV Community

Mohith
Mohith

Posted on

Reverse an Array-java

My Thought Process (Java DSA)

When I first looked at this problem on GeeksforGeeks, it seemed very simple. But instead of jumping directly into code, I tried to understand what is actually happening when we "reverse" an array.


Problem Statement

We are given an array of integers arr[].
The task is to reverse the array in-place, meaning we should not use any extra space.


Initial Thinking

If I take an example:

arr = [1, 4, 3, 2, 6, 5]
Enter fullscreen mode Exit fullscreen mode

The reversed array should be:

[5, 6, 2, 3, 4, 1]
Enter fullscreen mode Exit fullscreen mode

At first, I thought about creating a new array and filling it from the end. But then I noticed the constraint: modify the array in-place.

So using extra space is not a good approach here.


Key Observation

Reversing an array means:

  • First element goes to last
  • Second element goes to second last
  • And so on...

So instead of moving everything, I can just swap elements from both ends.


Approach (Two Pointer Technique)

I used two pointers:

  • left starting from index 0
  • right starting from index n - 1

Then I keep swapping:

  • arr[left] with arr[right]
  • Move left++
  • Move right--

Stop when left >= right


It should be Run like

arr = [1, 4, 3, 2, 6, 5]

Step 1:
swap(1, 5) → [5, 4, 3, 2, 6, 1]

Step 2:
swap(4, 6) → [5, 6, 3, 2, 4, 1]

Step 3:
swap(3, 2) → [5, 6, 2, 3, 4, 1]

Done
Enter fullscreen mode Exit fullscreen mode

Code in (Java)

class Solution {
    public void reverseArray(int arr[]) {
        int left = 0;
        int right = arr.length - 1;

        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;

            left++;
            right--;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

How This Works

  • We are not shifting elements
  • We are just swapping pairs
  • Each swap puts two elements in correct position
  • We only need to go till the middle of the array

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

This is optimal because:

  • We traverse the array only once
  • No extra memory is used

Final Thought

This problem is a basic example of the two-pointer technique.
Understanding this helps in many other problems like:

  • Palindrome checking
  • Two sum (sorted arrays)
  • String reversal

Instead of thinking complex, sometimes the best solution is just swapping from both ends.


Top comments (0)