Blind 75
18 / 75Free practice

Search in Rotated Sorted Array

Medium · Binary search

Jump to code

Search for a target in a rotated ascending array of distinct integers. Return its index, or −1 if it is absent, using logarithmic time.

Examples

Example 1

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

Output: 4

Example 2

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

Output: -1

Constraints

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -1000 <= target <= 1000
  • All values of nums are unique.
  • nums is an ascending array that is possibly rotated.
Need a hint?

At least one half around the midpoint is sorted.

Asked in real interviews

Candidates reported versions of Search in Rotated Sorted Array from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 11 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    4,
    5,
    6,
    7,
    0,
    1,
    2
  ],
  0
]
Expected
4
Case 2
Input
[
  [
    4,
    5,
    6,
    7,
    0,
    1,
    2
  ],
  3
]
Expected
-1
Case 3
Input
[
  [
    1
  ],
  0
]
Expected
-1
Case 4
Input
[
  [
    1,
    2,
    3,
    4,
    5
  ],
  4
]
Expected
3
Case 5
Input
[
  [
    6,
    7,
    1,
    2,
    3,
    4,
    5
  ],
  6
]
Expected
0

Drafts are saved per language in this browser when storage is available.