Overview
Given a sorted (ascending) array of integers nums and a target value target, return the index of target if found. Otherwise return -1.
Constraints
1 <= nums.length <= 10,000- All values in
numsare unique and sorted in ascending order. -10,000 <= nums[i], target <= 10,000- Must run in O(log n) time.
Examples
search([-1, 0, 3, 5, 9, 12], 9); // => 4 search([-1, 0, 3, 5, 9, 12], 2); // => -1
Solution
Reveal solution
function search(nums, target) {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}Resources
binary-search.js
Binary Search
easycodingAlgorithmsBinary Search
Overview
Given a sorted (ascending) array of integers nums and a target value target, return the index of target if found. Otherwise return -1.
Constraints
1 <= nums.length <= 10,000- All values in
numsare unique and sorted in ascending order. -10,000 <= nums[i], target <= 10,000- Must run in O(log n) time.
Examples
search([-1, 0, 3, 5, 9, 12], 9); // => 4 search([-1, 0, 3, 5, 9, 12], 2); // => -1
Solution
Reveal solution
function search(nums, target) {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}Resources
NameTopicDifficulty
103 of 103 problems