Reverse an array 2

Pattern: Recursion basics

easy

Reverse an array in place with recursion, by swapping the two ends and then reversing the inside.

The problem

You are given an array of whole numbers with between 1 and 1000 elements. Reverse it in place using recursion, and return it. For example, [1, 2, 3, 4, 5] becomes [5, 4, 3, 2, 1].

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name reverseArray and the limits above are this guide's own.

Think first

  • After you swap the first and last elements of [1, 2, 3, 4, 5], what is left to do? Is it a smaller copy of the same job?
  • How will you describe "the inside of the array" to the next call without copying it?
  • When should the recursion stop, for an odd length and for an even length?

Hints

    Brute force, and why it fails

    Build a new array by copying elements from the back to the front. That is correct and simple, but it uses a second array of the same size. The two-ends swap does the job in place. As a loop it uses constant memory; as a recursion it uses about n / 2 stack frames, which is the point of this exercise.

    The key insight

    Reversing is "swap the ends, then reverse the inside", and the inside is a smaller instance of the same task. Two indexes moving towards each other describe each smaller part without any copying.

    Dry run

    10left
    21 
    32 
    43 
    54right
    left0
    right4

    arr = [1, 2, 3, 4, 5]. Call swapEnds(arr, 0, 4). left is less than right, so there is work to do.

    Step 1 of 4

    The plan

    function reverseArray(arr):
        swapEnds(arr, 0, length(arr) - 1)
        return arr
    
    function swapEnds(arr, left, right):
        if left >= right:
            return                         # met in the middle
        swap arr[left] and arr[right]
        swapEnds(arr, left + 1, right - 1) # reverse the inside
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    About n / 2 calls, each doing one swap. The stack holds up to about n / 2 frames, which is O(n) memory. A loop version would use O(1).

    Edge cases

    • A single element: left = right = 0 from the start, so nothing changes.
    • Even length such as [1, 2, 3, 4]: after two swaps left = 2 and right = 1, so they have crossed and the call stops.
    • Repeated values swap like any others.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] reverseArray(int[] arr) {
            swapEnds(arr, 0, arr.length - 1);
            return arr;
        }
    
        private void swapEnds(int[] arr, int left, int right) {
            if (left >= right) {
                return;                             // base case: met in the middle
            }
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            swapEnds(arr, left + 1, right - 1);     // the inside is a smaller array
        }
    }

    C++

    class Solution {
    public:
        vector<int> reverseArray(vector<int>& arr) {
            swapEnds(arr, 0, static_cast<int>(arr.size()) - 1);
            return arr;
        }
    
        void swapEnds(vector<int>& arr, int left, int right) {
            if (left >= right) {
                return;                             // base case: met in the middle
            }
            swap(arr[left], arr[right]);
            swapEnds(arr, left + 1, right - 1);     // the inside is a smaller array
        }
    };

    Python

    class Solution:
        def reverseArray(self, arr):
            self.swapEnds(arr, 0, len(arr) - 1)
            return arr
    
        def swapEnds(self, arr, left, right):
            if left >= right:
                return                                  # base case: met in the middle
            arr[left], arr[right] = arr[right], arr[left]
            self.swapEnds(arr, left + 1, right - 1)     # the inside is a smaller array

    Common mistakes

    • Stopping only when left == right. For even lengths they never become equal, they cross, and the swaps start undoing each other.
    • Moving only one index each call.
    • Swapping with a temporary variable but writing the values back in the wrong order.

    Similar problems