Reverse the array
Problem
Given an array, reverse it in place so the first element becomes the last and so on. Return the same array.
Example 1
Input: [1, 2, 3, 4, 5] Output: [5, 4, 3, 2, 1]
Test cases
Case 1
Input: [1,2,3,4,5] Expected: [5,4,3,2,1]
Case 2
Input: [1,2] Expected: [2,1]
Case 3
Input: [7] Expected: [7]
Case 4
Input: [] Expected: []
View solutionHide solution2 approaches
1. Two pointers (in place)
Time O(n)Space O(1)
Swap the ends and walk inward until the pointers meet.
function reverse(a) { let l = 0, r = a.length - 1; while (l < r) { [a[l], a[r]] = [a[r], a[l]]; l++; r--; } return a;}2. Recursion
Time O(n)Space O(n) call stack
Swap outermost pair, recurse on the inner subarray. Shows recursion but costs stack.
function reverse(a, l = 0, r = a.length - 1) { if (l >= r) return a; [a[l], a[r]] = [a[r], a[l]]; return reverse(a, l + 1, r - 1);}