Element in Rotated Sorted Array

Let's modify the problem with a rotated sorted array and solve it. Difficulty Level: Medium

Problem statement

Suppose an array that was sorted in ascending order is rotated. For example, the array nums = [0,1,2,4,5,6,7] might become:

  • [4,5,6,7,0,1,2], if it is rotated 4 times.
  • [0,1,2,4,5,6,7], if it is rotated 7 times.

Notice that rotating an array [nums[0], nums[1], nums[2], ..., nums[n-1]] 1 time results in the array [nums[n-1], nums[0], nums[1], nums[2], ..., nums[n-2]].

Suppose we are given a sorted rotated array nums, and an integer target. If target is found in the array, we will return its index. Otherwise, we will return -1.

Constraints:

  • 1 \leq nums.length \leq 5000
  • -10^4 \leq nums[i] \leq 10^4
  • All of the values of nums are unique.
  • nums is guaranteed to be rotated at some pivot.
  • -10^4 \leq target \leq 10^4

Example 1:

Input: [4,5,6,7,0,1,2], 0    
Output: 4

Example 2:

Input: [4,5,6,7,0,1,2], 3    
Output: -1

Example 3:

Input: [1], 0    
Output: -1

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.