
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain two space-separated integers ‘N’ and ‘X’ where ‘N’ is the length of the array, and ‘X’ is the integer which is described above.
For each test case, print the index(0th based) of ‘X’ if it exists in the given array else print -1.
Output for every test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of.
1 <= T <= 50
1 <= N <= 10000
0 <= X <= 10^5
0 <= ARR[i] <= 10^5
Where ‘T’ is the number of test cases.
Where 'N' is the number of elements in the given array/list and ‘X’ is the integer which you need to search in the array.
And, ARR[i] denotes the value ith element of the input array.
Time limit: 1 sec
The basic idea is to iterate through all the elements of the array and find the position of ‘X’ if it exists in the array. Steps are as follows:
The basic idea of this approach is to do the modified binary search.
If the given array is sorted, we might do the binary search and can optimise our solution. But since it is rotated by an unknown value, the resulting array is no longer sorted.
We can observe the rotated array can be partitioned precisely into two fully sorted subarrays around a pivot index.
For instance, for the given array [6, 8, 9, 11, 15, 2, 3], the pivot point is an index 5(0th based indexing) and two sub-arrays are [6, 8, 9, 11, 15] and [2, 3]. Notice that each array is indeed fully sorted(in ascending order).
Now, our task is dependent on finding the pivot index. So how do we choose a pivot point?
Note that ith index is the pivot point if and only if ARR[i-1] > ARR[i] and there could be maximum only one such point since all the values of the array are distinct and the array was rotated to the left.
Now to find the pivot point, we could quickly scan the array linearly until we find an index that meets the condition for the pivot index. However, a more efficient way will be to use a modified version of the binary search. Steps are as follows:
The basic idea of this approach is to find the index of ‘X’ in a single pass of binary search instead of doing it as suggested in approach-2.
We will do the modified version of binary search in a single pass to get the index of ‘X’ if it exists.
Element Count in Ranges
First Digit One
Minimize Maximum Adjacent Distance
Sorted Doubly Linked List to Balanced BST
Minimized Maximum of Products Distributed to Any Store