I am trying to write a function to return a subset of a sorted input array where all the numbers are within the input range. For example:
getNumsWithin([1,2,3,5,6,7], [3.3, 6.7]) // [5, 6]
getNumsWithin([1,2,3,5,6,7], [6, 7]) // [6, 7]
getNumsWithin([1,2,3,5,6,7], [8, 10]) // []
Given the input array is always sorted, I assume I can use binary search to find a start index and an end index and just slice the original array with them.
Here is my attempt:
function findStartIdx(sortedArray, target) {
let start = 0,
end = sortedArray.length - 1
while (start < end) {
const mid = Math.floor((start + end) / 2)
if (sortedArray[mid] < target) start = mid
else end = mid - 1
}
return start + 1
}
function findEndIdx(sortedArray, target) {
let start = 0,
end = sortedArray.length - 1
while (start < end) {
const mid = Math.floor((start + end) / 2)
if (sortedArray[mid] < target) start = mid + 1
else end = mid
}
return end + 1
}
function getNumsWithin(array, range) {
const startIndex = findStartIdx(array, range[0])
const endIndex = findEndIdx(array, range[1])
return array.slice(startIndex, endIndex + 1)
}
But the binary search would end up being a endless loop if the target happens to the last num in the array. Also I wonder if we can just search it once instead of twice to find both the start and the
I am struggling to write such a function. can someone help me out?