Medium
Subtopics
array·binary-search
Companies
adobe·alibaba·amazon·apple·baidu·bloomberg·bytedance·cisco·ebay·expedia·facebook·goldman-sachs·google·ixl·jpmorgan·linkedin·microsoft·netease·nutanix·nvidia·oracle·paypal·salesforce·samsung·snapchat·tencent·tesla·tripadvisor·twitch·uber·visa·vmware·yahoo·yandex·zillow·zulilyLast updated: Mar 21, 2025
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array numsafter the possible rotation and an integer target, return the index oftargetif it is innums, or-1if it is not innums.
You must write an algorithm with O(log n) runtime complexity.
We can do a binary search with some modified checks. So lets take arr as array, start be start of the array, end be arr.length-1 and x be the number to find.
Ascertain the sorted segment of the array by comparing nums[mid] and nums[start].
If nums[mid] > nums[start] - That means this first part of array is sorted and is without rotation. So, we choose array to search as [start] to nums[mid]
Otherwise we choose nums[nums] to nums[end].
Now, depending on the array we searched in step 2, we will get the sorted array now. Now if key target lies in range of the array, we will search for the element in that range, otherwise other range.
So, second step helps us get the sorted array on which we can apply binary search.