← All Exercises
Search in a Rotated Sorted Array
intermediatepython
Background
A rotated sorted array still has one sorted half around the midpoint; comparing endpoints reveals which half can contain the target.
Problem
Given an array of distinct integers that was sorted then rotated, return the index of target in O(log n), or -1 if it is absent. Do not sort or scan the array.
Input
A rotated sorted list of distinct integers and a target integer.
Output
The index of the target, or -1 when it is not present.
Sample tests
Sample 1
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Expected: 4
Sample 2
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Expected: -1
Sample 3
Input: nums = [1, 3, 5], target = 3
Expected: 1
Your solution
Learning objective
Adapt binary search to a rotated sorted array by identifying the sorted half before choosing the next range.