Challenge 2: Search First Occurrence of a Number

Given an array, find the first occurrence of the target number.

Problem Statement

Implement a function that takes an array arr, a testVariable (containing the number to search) and currentIndex (containing the starting index) as parameters. This function should output the index of the first occurrence of testVariable in arr. If testVariable is not found in arr it should return 1-1.

Try to implement your solution recursively.

Input

  1. A variable arr that contains the array that will be searched.
  2. A variable testVariable, being the number that will be searched.
  3. A variable currentIndex that contains the starting index of the arr array.

Output

Index of the first occurrence of testVariable in arr

Sample Input

arr = [9, 8, 1, 8, 1, 7]
targetNumber = 1
currentIndex = 0

Sample Output

2

Try it Yourself!

Try this challenge yourself before examining the solution. Goodluck!

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.