Search in Rotated Sorted Array

Try to solve the Search in Rotated Sorted Array problem.

Statement

Given a sorted integer array, nums, and an integer value, target, the array is rotated by some arbitrary number. Search and return the index of target in this array. If the target does not exist, return -1.

An original sorted array before rotation is given below:

g array 1 10 20 47 59 63 75 88 99 107 120 133 155 162 176 188 199 200 210 222

After rotating this array 6 times, it changes to:

g array 176 188 199 200 210 222 1 10 20 47 59 63 75 88 99 107 120 133 155 162

Constraints

  • All values in nums are unique.
  • The values in nums are sorted in ascending order.
  • The array may have been rotated by some arbitrary number.
  • 11 \leq nums.length 1000\leq 1000
  • 104-10^4 \leq nums[i] 104\leq 10^4
  • 104-10^4 \leq target 104\leq 10^4

Examples

1 of 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:

Search in Rotated Sorted Array

1

What is the output if the following rotated sorted array and target are given as input?

nums = [4, 5, 6, 7, 0, 1, 2]

target = 1

A)

0

B)

1

C)

5

D)

6

Question 1 of 30 attempted

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence

Try it yourself

Implement your solution in the following coding playground:

Press + to interact
Python
usercode > main.py
def binary_search_rotated(nums, target):
# Replace this placeholder return statement with your code
return -1
Search in Rotated Sorted Array