← Back to libraryQuestion 92 of 273
⌨️Java CodingBeginner

Reverse an Array In Place

📌 Definition:

Reverse the order of elements of an array without allocating a second array.

📖 Detailed Explanation:

Swap elements from both ends toward the middle with two pointers — O(n) time, O(1) space. This is the array analog of string reversal and the building block for the rotate-by-k trick.

💻 Solutions:
public static void reverse(int[] a) {
    int i = 0, j = a.length - 1;
    while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
}
function reverse(a) {
  let i = 0, j = a.length - 1;
  while (i < j) { [a[i], a[j]] = [a[j], a[i]]; i++; j--; }
  return a;
}
def reverse(a):
    i, j = 0, len(a) - 1
    while i < j:
        a[i], a[j] = a[j], a[i]
        i += 1
        j -= 1
    return a
🔑 Key Points:
  • Two pointers swapping toward the middle
  • In place — O(1) extra space
  • O(n) time
  • Foundation for array rotation
🌍 Real-World Example:

In-place reversal is a fundamental primitive reused by rotation, palindrome checks, and undo/redo style buffers.

🎯 Scenario-Based Interview Question:

What is the advantage of the in-place swap over building a new reversed array?