Skip to content

Binary Search 02 Completed #1910

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
47 changes: 47 additions & 0 deletions find_first_and_last_position_array_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
let firstIndex = binarySearch(nums, 0, nums.length - 1, target, -1);
if (firstIndex == -1) {
return [-1, -1];
}
let lastIndex = binarySearch(nums, firstIndex, nums.length - 1, target, 1);
return [firstIndex, lastIndex];
};

var binarySearch = function (nums, left, right, target, direction) {
while (left <= right) {
let mid = Math.round(left + (right - left) / 2);
if (nums[mid] == target) {
let nextIndex = mid + direction;
if (nextIndex >= 0 && nextIndex <= right && nums[nextIndex] == target) {
if (nextIndex > mid) {
left = nextIndex;
} else if (nextIndex < mid) {
right = nextIndex;
} else {
return mid;
}
} else {
return mid;
}
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
};

test("Scenario #1: [5, 7, 7, 8, 8, 10]", () => {
let result = searchRange([5, 7, 7, 8, 8, 10], 8);
let expected = [3, 4];
expect(result).toStrictEqual(expected);
});
test("Scenario #2: [3, 3, 3]", () => {
expect(searchRange([3, 3, 3], 3)).toStrictEqual([0, 2]);
});
33 changes: 33 additions & 0 deletions find_minimum_in_rotated_array_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @param {number[]} nums
* @return {number}
*/
var findMin = function (nums) {
let left = 0;
let right = nums.length - 1;

while (left < right) {
let mid = Math.round(left + (right - left) / 2);
let element = nums[mid];
// If left half is sorted the move search range to right side
// else left side.

if (element < nums[right]) {
// Move Left
right = mid;
} else {
left = mid;
}
}
return left;
};

test("Scenario #1: [5,6,7,1,2,3,4]", () => {
expect(findMin([5, 6, 7, 1, 2, 3, 4])).toStrictEqual(3);
});
test("Scenario #2: [3, 1, 2]", () => {
expect(findMin([3, 1, 2])).toStrictEqual(1);
});
test("Scenario #3: [1, 2, 3]", () => {
expect(findMin([1, 2, 3])).toStrictEqual(123);
});