DSA Problems/πŸ”Binary Search

Search in Rotated Sorted Array

ArrayBinary Search

Problem Statement

Given an integer array nums sorted in ascending order and rotated at some pivot, and an integer target, return the index of target if it is in nums, or -1 if it is not.

You must write an algorithm with O(log n) runtime complexity.

Approach

Modified binary search. Determine which half is sorted, then decide which half to search.

Complexity Analysis

MetricValue
TimeO(log n)
SpaceO(1)

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

Constraints

  • β–Έ1 <= nums.length <= 5000
  • β–Έ-10^4 <= nums[i] <= 10^4
  • β–ΈAll values of nums are unique
  • β–Έnums is sorted and rotated at some pivot
Loading...
Sign in to run your code...

Asked by companies:

AmazonFacebookMicrosoftLinkedIn