FrontendInterviews.dev

Loading problem…

99. Search in Rotated Sorted Array

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

You're building a search feature for data that might be rotated. This extends binary search to handle rotated sorted arrays.

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]].

Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

Requirements

1. Basic Functionality

  • Search for target in rotated sorted array
  • Array was originally sorted but rotated
  • Return index if found, -1 if not found
  • O(log n) time complexity

Example Usage

search([4,5,6,7,0,1,2], 0); // 4
search([4,5,6,7,0,1,2], 3); // -1
search([1], 0); // -1

Real-World Context

This problem models real search scenarios:

  • Rotated data: Search in rotated sorted arrays
  • Circular buffers: Search in circular data structures
  • Binary search extension: Advanced binary search
  • Performance: O(log n) search in rotated arrays

Constraints

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values are unique
  • nums is rotated at some pivot