Skip to content

33. Search in Rotated Sorted Array #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions solutions/searchInRotatedSortedArray.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
32 changes: 32 additions & 0 deletions solutions/searchInRotatedSortedArray.ts
Original file line number Diff line number Diff line change
@@ -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;
}