Search⌘ K

Solution Review: Search First Occurrence of a Number

Explore the process of finding the first occurrence of a number in an array using both iterative and recursive methods in Python. Learn how to implement each solution, understand their base and recursive cases, and compare the efficiency of iteration versus recursion in practical coding challenges.

Solution #1: Iterative Method

Python 3.5
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
return -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

...