diff --git a/solutions/searchInRotatedSortedArray.test.ts b/solutions/searchInRotatedSortedArray.test.ts new file mode 100644 index 0000000..a3ba792 --- /dev/null +++ b/solutions/searchInRotatedSortedArray.test.ts @@ -0,0 +1,23 @@ +import search from "./searchInRotatedSortedArray"; + +describe("33. Search in Rotated Sorted Array", () => { + test("#1", () => { + expect(search([4, 5, 6, 7, 0, 1, 2], 0)).toBe(4); + }); + + test("#2", () => { + expect(search([4, 5, 6, 7, 0, 1, 2], 3)).toBe(-1); + }); + + test("#3", () => { + expect(search([4, 5, 6, 7, 0, 1, 2], 4)).toBe(0); + }); + + test("#4", () => { + expect(search([3, 1], 3)).toBe(0); + }); + + test("#5", () => { + expect(search([7, 8, 1, 2, 3, 4, 5, 6], 2)).toBe(3); + }); +}); diff --git a/solutions/searchInRotatedSortedArray.ts b/solutions/searchInRotatedSortedArray.ts new file mode 100644 index 0000000..f7278ba --- /dev/null +++ b/solutions/searchInRotatedSortedArray.ts @@ -0,0 +1,32 @@ +// 33. Search in Rotated Sorted Array +// https://leetcode.com/problems/search-in-rotated-sorted-array/ +export default function search(nums: number[], target: number): number { + // check if the target value is inside a range that may be rotated + function isInRangeMaybeRotated(from: number, to: number) { + const fromValue = nums[from]; + const toValue = nums[to]; + + // the range is looped when the from value is greater than the to value + if (fromValue > toValue) return target >= fromValue || target <= toValue; + + // when the range is not looped, target must be between the from value and the to value + return target >= fromValue && target <= toValue; + } + + let from = 0; + let to = nums.length; + + while (from < to) { + const middle = Math.floor((from + to) / 2); + + if (nums[middle] === target) return middle; + + if (isInRangeMaybeRotated(from, middle - 1)) { + to = middle; + } else { + from = middle + 1; + } + } + + return -1; +}