Search in Rotated Sorted Array
A sorted array of distinct numbers was rotated: some numbers from its start moved to its end, keeping their order. Find the index of a target, or return −1 if it is not there, in O(log n) time. Our example: [12, 19, 25, 31, 36, 2, 5, 9] and 5 — the answer is 6.
- input
nums: different integers in ascending order, rotated: moved round by some places, so[1, 3, 5, 7]may come as[5, 7, 1, 3]or as it was;target: an integer.- returns
- The index of
targetinnums, or-1if it is not there. LeetCode wants it in O(log n). - constraints
- 1 ≤ nums.length ≤ 5000
- −10⁴ ≤ nums[i] ≤ 10⁴
- nums is an ascending array of different numbers, rotated
- −10⁴ ≤ target ≤ 10⁴
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
function search(nums, target) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more binary search problems
- 704Binary SearchEasysolve
- 35Search Insert PositionEasysolve
- 69Sqrt(x)Easysolve
- 153Find Minimum in Rotated Sorted ArrayMediumsolve
- 875Koko Eating BananasMediumsolve
- 1011Capacity To Ship Packages Within D DaysMediumsolve
- 274H-IndexMediumsolve
- 74Search a 2D MatrixMediumsolve
- 162Find Peak ElementMediumsolve
- 34Find First and Last Position of Element in Sorted ArrayMediumsolve
- 4Median of Two Sorted ArraysHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.