Skip to content

Instantly share code, notes, and snippets.

@rtsoy
Last active January 1, 2026 15:22
Show Gist options
  • Select an option

  • Save rtsoy/1510b1bbd86cb1ea9f8f9b027f5239f3 to your computer and use it in GitHub Desktop.

Select an option

Save rtsoy/1510b1bbd86cb1ea9f8f9b027f5239f3 to your computer and use it in GitHub Desktop.
33. Search in Rotated Sorted Array
// https://leetcode.com/problems/search-in-rotated-sorted-array/
//
// Time: O(log n)
// Space: O(1)
//
// n = number of elements in the array
// .................... //
func search(nums []int, target int) int {
n := len(nums)
last := nums[n-1]
lo, hi := 0, n-1
for lo <= hi {
mi := lo + (hi-lo)/2
if nums[mi] > last {
lo = mi + 1
} else {
hi = mi - 1
}
}
min := lo
if target > last {
lo, hi = 0, min
} else {
lo, hi = min, n-1
}
for lo <= hi {
mi := lo + (hi-lo)/2
if nums[mi] == target {
return mi
}
if nums[mi] > target {
hi = mi - 1
} else {
lo = mi + 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment