How to reverse an array?
1. The two-pointer algorithm
Idea: Swap elements from the start and the end of the array, gradually moving toward the center.
javascript
function reverseArray(arr) {
let left = 0
let right = arr.length - 1
while (left < right) {
// Swap arr[left] and arr[right]
const temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left++
right--
}
return arr
}
// Example:
console.log(reverseArray([1, 2, 3, 4, 5])) // [5, 4, 3, 2, 1]Complexity
- Time:
O(n) - Memory:
O(1), no new array is created.
2. Reversing without changing the original array
If the task does not allow changing the original array, you can create a new one:
javascript
function reversedCopy(arr) {
const result = []
for (let i = arr.length - 1; i >= 0; i--) {
result.push(arr[i])
}
return result
}
console.log(reversedCopy([10, 20, 30])) // [30, 20, 10]Complexity
- Time:
O(n) - Memory:
O(n), a new array.
3. Via recursion (less common, but often asked about)
javascript
function reverseRecursive(arr, left = 0, right = arr.length - 1) {
if (left >= right) return arr
const temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
return reverseRecursive(arr, left + 1, right - 1)
}
console.log(reverseRecursive([1, 2, 3, 4])) // [4, 3, 2, 1]Recursion is less memory-efficient (the call stack), but it neatly demonstrates the "edges to center" logic.
Summary
| Method | Changes the array | Time | Memory | Notes |
|---|---|---|---|---|
| Two pointers | Yes | O(n) | O(1) | The optimal approach |
| Loop with a new array | No | O(n) | O(n) | Does not modify the original |
| Recursion | Yes | O(n) | O(n) | Less efficient, but illustrative |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.