Invert an Array

In this lesson, we will learn how to inverse an array recursively.

What does “Invert an Array” mean?

Our task here is to make the first element of the array the last element, the second element the second last element and so on.

Inverting an array
Inverting an array

Implementation

Press + to interact
def reverse(array):
# Base case1
if len(array) == 0: # If we encounter an empty array, simply return an empty array
return []
# Base case2
elif len(array) == 1 : # Inverting an array of size 1 returns the same array
return array
# Recursive case
return [array[len(array) - 1]] + reverse(array[:len(array) - 1])
# The first part is storing the last element to be appended later
# The second part is calling another instance of the same function with the last element removed
# Driver Code
array = [1, 2, 3, 4]
print(reverse(array))

Explanation

In the code snippet above, we break the last element of the array, which will later be added in the front of the array.

We keep breaking the last element and saving it for appending in the front of the array in each function call until we reach an empty array. Here, the empty array will be our base case, because we simply return the empty array []. After the base case is satisfied, the rest of the elements are appended in the reverse order. Hence, when the last function returns we have an inverted array.

The sequence of function calls is as follows:


In the next lesson, we will learn how to replace all negative numbers with 00 using recursion.