
The first line of input contains the size of the array: N
The second line contains N single space-separated integers: A[i].
The third line of input contains the number of queries: Q
The next Q lines of input contain: the number which Sam wants Ninja to search: Q[i]
For each test case, print the index of the number if found, otherwise -1.
Output for every test case will be printed in a separate line.
You are not required to explicitly print the expected output, just return it and printing has already been taken care of.
1 <= N <= 10^6
-10^9 <= A[i] <= 10^9
1 <= Q <= 500
-10^9 <= Q[i] <= 10^9
Time Limit: 1sec
Before we discuss the algorithm, there's an interesting property about sorted and rotated arrays that must be noted.
If we divide the array into two halves, at least one of the two halves will always be sorted.
Let's consider the array: [5, 6, 7, 1, 2, 3, 4]
5 6 7 1 2 3 4
Mid-index is calculated as (startIndex + endIndex) / 2 or start + (endIndex - startIndex) / 2.
The mid-index for the above-depicted list/array will be 3.
The value at the mid-index is 1. If we have a closer look at three values, that are, value at start, end, and mid then we can deduce which the subarray is sorted or not.
Since the value at the mid-index is less than the value at the start index, we clearly can say that the left subarray is not sorted or violates the property of a sorted array.
Similarly, we can deduce if the right subarray is sorted or not by comparing the values at mi-index and end index.
Now, once we know what part of the array is sorted, we can compare the value(key) to be searched in reference to the sorted subarray.
Finally, to put everything in points: