# LeetCode: Search in Rotated Sorted Array Solution

*Time-boxing and other solutions make life easier*

## Approach

Case when

nums[begin, mid]

is sorted- if targetis in the range, decreaseend, otherwise increasebegin

Case when

nums[mid + 1, end]

is sorted- if targetis in the range, increasebegin, otherwise decreaseend

## Implementation

1var search = function (nums, target) {2 let n = nums.length3 let [begin, end] = [0, n - 1]4 let res = -156 while (begin <= end) {7 let mid = Math.floor((begin + end) / 2)89 if (nums[mid] === target) {10 res = mid11 break12 }1314 if (nums[begin] <= nums[mid]) {15 if (nums[begin] <= target && target <= nums[mid]) {16 end = mid - 117 } else {18 begin = mid + 119 }20 } else {21 if (nums[mid] <= target && target <= nums[end]) {22 begin = mid + 123 } else {24 end = mid - 125 }26 }27 }2829 return res30}

## References

## Similar problems

Search in Rotated Sorted Array II

Find Minimum in Rotated Sorted Array

Pour Water Between Buckets to Make Water Levels Equal

## Comments

Loading comments...

## Tags

leetcode

array

binary search

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.