Challenge 2: Search the First Occurrence of a Number
Given an array, find the first occurrence of a given target number.
We'll cover the following
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 and outputs the index of the first occurrence of testVariable
in arr
. If testVariable
is not found in arr
return .
We want to search for a targetNumber
from index currentIndex
to the end of the array.
Try to implement your solution recursively.
Input
- A variable
arr
that contains the array on which searching is to be performed. - A variable
testVariable
that contains the number that needs to be searched. - A variable
currentIndex
that contains the starting index of thearr
array.
Output
Index of the first occurrence of testVariable
in arr
.
Sample Input
arr = [9, 8, 1, 8, 1, 7];
testVariable = 1;
currentIndex = 0;
Sample Output
2
Try it Yourself
Try this challenge yourself before examining the solution. Good luck!
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.