Problem 93
Search in Rotated Sorted Array
Medium · 20 pts · Array, Binary Search
Problem
An array of distinct integers was sorted in increasing order and then rotated at an unknown position: the elements from that position onwards were moved to the front. For example, 0 1 2 4 5 6 7 can become 4 5 6 7 0 1 2. Given the rotated array and a target T, print the index of T, or -1 if it is not present. Aim for O(log N). In a binary search, at least one half around the middle element is always sorted. Check whether T lies within the sorted half's range; if so, search there, otherwise search the other half.
Input
First line: integers N and T. Second line: the N rotated array values.
Output
Print the zero-based index of T, or -1.
Constraints
1 <= N <= 100000; -1000000000 <= A[i], T <= 1000000000; values are distinct
Example input
7 0 4 5 6 7 0 1 2
Example output
4
Explanation
In 4 5 6 7 0 1 2, the target 0 sits right after the rotation point, at index 4.