Inplace Reverse of an Array

Concept Description

The concept of reversing an array “in-place” refers to transforming an array so that its elements are in the opposite order, but doing this within the same array to conserve memory. “In-place” means we won’t use an additional array to perform this operation, making it a space-efficient approach. This operation typically involves swapping elements in a specific manner.

Example Code

Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Main {
  public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5};
    reverseArray(arr);
    for (int num : arr) {
      System.out.print(num + " ");
    }
  }

  public static void reverseArray(int[] arr) {
    int start = 0, end = arr.length - 1;
    while (start < end) {
      // Swap elements at start and end
      int temp = arr[start];
      arr[start] = arr[end];
      arr[end] = temp;

      start++;
      end--;
    }
  }
}
C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

void reverseArray(int arr[], int n) {
  int start = 0, end = n - 1;
  while (start < end) {
    // Swap elements at start and end
    swap(arr[start], arr[end]);

    start++;
    end--;
  }
}

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int n = sizeof(arr) / sizeof(arr[0]);
  reverseArray(arr, n);
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  return 0;
}
Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def reverse_array(arr):
    start, end = 0, len(arr) - 1
    while start < end:
        # Swap elements at start and end
        arr[start], arr[end] = arr[end], arr[start]

        start += 1
        end -= 1

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    reverse_array(arr)
    print(arr)

By using this “in-place” reversal technique, we can reverse an array with O(1) additional space, making it a memory-efficient approach. The time complexity remains O(n/2), which simplifies to O(n).