Coders Crushby Napplied AI
Back to DSA Problems
MediumLeetCode #33Binary Search

Search in Rotated Sorted Array

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. Given the array nums after rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

Constraints
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • AI Discovery

Coders Crush by Napplied AI - Built for engineers preparing for FAANG/MAANG interviews

1 <= nums.length <= 5000, -10^4 <= nums[i] <= 10^4, All values of nums are unique
Examples
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Solution

Approach

Modified binary search. At each step, one half is always sorted. Check if target is in the sorted half, otherwise search the other half.

def search(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        if nums[left] <= nums[mid]:
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        else:
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1
    return -1
Complexity
Time:O(log n)
Space:O(1)
Hints
  • 1.One half is always sorted after rotation
  • 2.Determine which half is sorted
  • 3.Check if target falls in sorted half
Asked at
GoogleAmazonMetaAppleMicrosoftLinkedInBloomberg