Search in Rotated Sorted Array

TCS NQT Coding Medium Go Ad-Free - ₹20/mo

Given a sorted array of distinct integers that has been rotated at an unknown pivot index, and an integer target, search for the target in the array. The array may be rotated, meaning it consists of two sorted subarrays. Return the index of the target if it exists, otherwise return -1. The solution must achieve O(log n) time complexity by leveraging a modified binary search approach.

Examples:

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

Output: 4

Explanation: Target 0 is at index 4 in the rotated array.

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

Output: -1

Explanation: Target 3 is not present in the array.

Input: nums = [1], target = 0

Output: -1

Constraints

  • The array is rotated at some pivot index (could be 0, meaning no rotation).
  • All elements in the array are distinct.
  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= target <= 10^4