Replace all Negative Numbers with Zero
In this lesson, we will learn how to replace all negative numbers with 0 in an array recursively.
We'll cover the following
What does “Replace all Negative Numbers with 0” Mean?
An array can contain any number of negative numbers. Our task is to replace all instances of negative numbers with , starting from a given index of the array.
We will not be creating a new array. We will be modifying the same array.
Implementation
def replace(array, currentIndex) :if currentIndex < len(array) :if array[currentIndex] < 0 :array[currentIndex] = 0replace(array, currentIndex + 1)return# Driver Codearray = [2, -3, 4, -1, -7, 8]print("Original Array --> " + str(array))replace(array, 0)print("Modified Array --> " + str(array))
Explanation
For this problem, it is easier to think of an iterative solution first. If we think of the solution iteratively we would have come up with a solution as follows:
currentIndex = 0
while(currentIndex < len(array) :
if array[currentIndex] < 0 :
array[currentIndex] = 0
currentIndex += 1
Now, it is easier to map this to a recursive solution. The local variable currentIndex
becomes the parameter of the function and in each child function call, the currentIndex
is increased by .
In the iterative version in each iteration we were checking for negative numbers:
if array[currentIndex] < 0 :
array[currentIndex] = 0
Now, in the recursive version in each recursive call we will check the same.
At the beginning of the course, we stated that each recursive function has a base case and a recursive case. What will be the base case for the above code?
The sequence of function calls illustrated below will help you visualize the code better:
In the next lesson, we have a challenge for you to solve for yourself.