Skip to content
Merged
Changes from 1 commit
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
Next Next commit
Create 0034-find-first-and-last-position-of-element-in-sorted-array.js
Solved find-first-and-last-position-of-element-in-sorted-array in js.
  • Loading branch information
aadil42 authored Jun 22, 2023
commit 5020e65ee8a1d216bfd33e1f9a787bae9d4444e8
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));
result.push(binarySearch(false));

function binarySearch(leftBias) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: name booleans that prompt a question

isLeftBias

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a kind reminder that I updated the code as suggested.

let left = 0;
let right = nums.length - 1;
let index = -1;

while(left <= right) {

const mid = Math.floor((left+right)/2);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use bitwise

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


if(target > nums[mid]) {
left = mid+1;
}
if(target < nums[mid]) {
right = mid-1;
}
// this is the meat of the code
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Remove comment and creat descriptive variables or functions

const isTarget = (...);
if (isTarget) { ... }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.

if(target === nums[mid]) {
if(leftBias) {
index = mid;
right = mid - 1;
} else {
index = mid;
left = mid + 1;
}
}
}

return index;
}

return result;
};