Applied AI Engineer (LLM) coding learning path Level 2 This level · 28 of 31

Search in Rotated Sorted Array

Medium Binary search

Problem

Given an array of distinct values that was sorted in ascending order and then rotated, return the index of a target, or -1 if it is not present, in O(log n) time.

Original: LeetCode 33: Search in Rotated Sorted Array.

Examples

Example 1

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

Example 2

Input`nums = [4, 5, 6, 7, 0, 1, 2], target = 3`
Output`-1`

Example 3

Input`nums = [1], target = 0`
Output`-1`

Example 4

Input`nums = [1], target = 1`
Output`0`

Constraints

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique.
  • nums is an ascending array that is possibly rotated.
  • -10^4 <= target <= 10^4

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 33: Search in Rotated Sorted Arrayleetcode.com
Previous
Next