Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2620 from aadil42/patch-63
Browse files Browse the repository at this point in the history
  • Loading branch information
aakhtar3 authored Jul 22, 2023
2 parents 285999d + fe9c706 commit 0d6f0ea
Showing 1 changed file with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Binary Search
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
* Time O(log(n)) | Space O(1)
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {

const result = [];

result.push(binarySearch(true, nums, target));
result.push(binarySearch(false, nums, target));

return result;
};

var binarySearch = (isLeftBias, nums, target) => {
let left = 0;
let right = nums.length - 1;
let index = -1;

while(left <= right) {

const mid = (left + right) >> 1;

if(target > nums[mid]) {
left = mid+1;
}
if(target < nums[mid]) {
right = mid-1;
}

const isTarget = target === nums[mid];
if(isTarget) {
if(isLeftBias) {
index = mid;
right = mid - 1;
} else {
index = mid;
left = mid + 1;
}
}
}
return index;
}

0 comments on commit 0d6f0ea

Please sign in to comment.