Solution
To solve the Multiple Search Problem, let’s first look at the Binary Search Problem to search a single key in a sorted array of keys.
Sorted Array Search Problem
Search a key in a sorted array of keys.
Input: A sorted array of distinct integers (i.e.,) and an integer .
Output: Check whether occurs in .
A naive way to solve this problem is to scan the array (running time ). The algorithm below solves the problem in time. It is initialized by setting equal to and equal to . It sets to and then checks to see whether is greater than or less than []. If is larger than this value, then iterates on the subarray of from to ; otherwise, it iterates on the subarray of from to . The iteration eventually identifies whether occurs in .
0
while :
⌊()/ 2⌋
if [] :
return
else if [] q:
else:
return “key not found”
For example, if and , would first set , , and . Since is greater than [] , we examine the subarray whose elements are greater than [] by setting , so that is recomputed as . This time, is smaller than [] , and so we examine the subarray whose elements are smaller than this value. This subarray consists of a single element, which is .
The running time of is since it reduces the length of the subarray by at least a factor of at each iteration of the while loop. Note however that our grading system is unable to check whether you implemented a fast algorithm for the sorted array search or a naive algorithm. The reason is that any program needs a linear time in order to just read the input data. For this reason, we asked you to solve the multiple search problem.
Code
Here is an implementation of the challenge. Hit the “Run” button and observe the output.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.