Menu
CoddyTech

Search in Rotated Sorted Array

MediumBinary searchpython iconjava iconcpp iconc iconjs icon+10

A list of distinct integers was sorted in increasing order and then rotated: some number of elements, possibly zero, were taken from the front and moved to the back in the same order. For example, [2, 5, 8, 11, 15, 19, 23] rotated by 4 becomes [15, 19, 23, 2, 5, 8, 11]. You get the rotated list nums and an integer target. Return the index of target in nums, counting from 0, or -1 if it is not there, in O(log n) time.

Function

search(nums: integer-array, target: integer) → integer
numsinteger-array
the rotated sorted list of distinct integers
targetinteger
the value to look for
Returnsinteger
the index of target in nums, or -1 if it is missing

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -104 ≤ nums[i], target ≤ 104
  • All values in nums are distinct.
  • nums is an increasing list rotated by some k with 0 ≤ k < nums.length; k = 0 leaves it unrotated.

Examples

Input
nums = [15, 19, 23, 2, 5, 8, 11]target = 5
Output
4
Explanation
5 sits at index 4. The first middle, index 3, holds 2, so the right half [2, 5, 8, 11] is the sorted one, and 5 lies between 2 and 11. The next middle, index 5, holds 8; the sorted left part [5, 8] holds 5, which leads to index 4.

lock icon+23 hidden tests on Submit

challenge icon

Follow-up

If nums may contain duplicates, no algorithm can promise O(log n). Can you prove it? Build a rotated list of 1s with a single 0 hidden in it, where any search for 0 has to read every element.

Reset code
def search(nums, target):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [15, 19, 23, 2, 5, 8, 11]
target = 5

Expected

4