Solution Review: Search First Occurrence of a Number

This review provides a detailed analysis of finding the first occurrence of the given number in an array.

Solution #1: Iterative Method

Press + to interact
def firstIndex(arr, testVariable, currentIndex): # returns the first occurrence of testVariable
while currentIndex < len(arr) : # Iterate over the array
if arr[currentIndex] == testVariable : # Return the current index if testVariable found
return currentIndex
currentIndex += 1
# Driver Code
arr = [9, 8, 1, 8, 1, 7]
testVariable = 1
currentIndex = 0
print(firstIndex(arr, testVariable, currentIndex))

Explanation

To find the first occurrence of testVariable we iterate over the entire array and return the currentIndex when testVariable is found. Let’s look at an illustration:

Solution #2: Recursive Method

Press + to interact
def firstIndex(arr, testVariable, currentIndex) : # returns the first occurrence of testVariable
# Base Case1
if len(arr) == currentIndex :
return -1;
# Base Case2
if arr[currentIndex] == testVariable :
return currentIndex
# Recursive Case
return firstIndex(arr, testVariable, currentIndex + 1)
# Driver Code
arr = [9, 8, 1, 8, 1, 7]
testVariable = 1
currentIndex = 0
print(firstIndex(arr, testVariable, currentIndex))

Explanation

In the iterative method, we were reducing the length of the array in each iteration.

We will follow the same method: we will decrease the length of the array each time and pass it to another execution instance of the same function. This will be our recursive case.

For the base case, we will have two conditions:

  1. When the length of the array is equal to the currentIndex. This would mean that the entire array has been recursively traversed and still the testVariable has not been found. In this case, we return 1-1.
    if len(arr) == currentIndex :
        return -1;
  1. When testVariable is found at the currentIndex. In this case, we return the currentIndex.
    if arr[currentIndex] == testVariable :
        return currentIndex

The illustration below describes the solution in detail.


Let’s try another challenge in the next lesson.