# LeetCode: Search in Rotated Sorted Array Solution

Time-boxing and other solutions make life easier

## Approach

Case when

nums[begin, mid]
is sorted

• if
target
is in the range, decrease
end
, otherwise increase
begin

Case when

nums[mid + 1, end]
is sorted

• if
target
is in the range, increase
begin
, otherwise decrease
end

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var search = function (nums, target) {2  let n = nums.length3  let [begin, end] = [0, n - 1]4  let res = -15
6  while (begin <= end) {7    let mid = Math.floor((begin + end) / 2)8
9    if (nums[mid] === target) {10      res = mid11      break12    }13
14    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  }28
29  return res30}```

Original problem

## Similar problems

Search in Rotated Sorted Array II

Find Minimum in Rotated Sorted Array

Pour Water Between Buckets to Make Water Levels Equal

leetcode

array

binary search

## Next Post

CodeWars: Sudoku Solution Validator

Sep 14, 2022

Three checks

## Previous Post

LeetCode: Search a 2D Matrix

Sep 12, 2022

Flatten into 1D array

Search Posts