DDSA Solutions

Reverse an Array

Time: O(n)
Space: O(1)
Advertisement

Intuition

Reverse an array in-place. Two-pointer swap from both ends.

Algorithm

  1. 1Left=0, right=n-1. While left < right: swap, left++, right--.

Common Pitfalls

  • O(n) O(1). Fundamental operation. Same as LC 344 for strings.
Reverse an Array.java
Java
// Approach: Two-pointer swap from both ends towards center.
// Time: O(n) Space: O(1)
class Solution {
    public void reverseArray(int arr[]) {
        int i = 0, j = arr.length - 1;
        while (i <= j) {
            int c = arr[i];
            arr[i] = arr[j];
            arr[j] = c;

            i++;
            j--;
        }
    }
}
Advertisement
Was this solution helpful?