AlgoViz

Reverse an array

Easy

Swap the ends, recurse inward

Problem

Reverse an array in place using recursion (or two pointers).

In simple words

Swap the outer pair, then recurse on the inside — meeting in the middle.

The idea

Swap the first and last elements, then solve the same problem on the interior. The recursion stops when the pointers meet or cross, which is exactly the two-pointer loop written as a function.

The trick

  • Base case: left >= right.
  • Only n/2 swaps are needed — going further undoes your work.
  • The iterative two-pointer version is the same algorithm in O(1) space.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

1
2
3
4
5
0
1
2
3
4

Step 1 of 2. Here's the example — [1,2,3,4,5] Values: 1, 2, 3, 4, 5.

1/2
Optimal
timeO(n)spaceO(n)
1f(l,r):2  if l>=r: return3  swap(a[l],a[r])4  f(l+1,r-1)

Input

array
[1, 2, 3, 4, 5]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
nums = [1, 2, 3, 4]
Output:
[4, 3, 2, 1]
Explanation:
Swap ends and recurse inward.

Example 2

Input:
nums = [5, 6]
Output:
[6, 5]
Explanation:
Two elements swap.

Example 3

Input:
nums = [7]
Output:
[7]
Explanation:
One element stays.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.