Searching
Binary Search First Occurrence
Find the first copy of a duplicated target by recording matches and continuing to search the left half.
Algorithm
Basic Implementation
basic.js
const arr = [1, 2, 4, 4, 4, 7, 9];
const target = 4;
let lo = 0;
let hi = arr.length - 1;
let result = -1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (arr[mid] === target) {
result = mid;
hi = mid - 1;
} else if (arr[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
console.log(result);
Complexity
- Time: O(log n)
- Space: O(1)
Implementation notes
- JavaScript stores
arras aconstArrayofNumbervalues and searches it without mutating the array or calling a library helper. - The iterative loop keeps
let lo,let hi, andlet result = -1as local numeric bindings.resultis the miss sentinel until a matching index is recorded. - Each probe computes
const mid = lo + Math.floor((hi - lo) / 2), then readsarr[mid]. Strict equality,arr[mid] === target, records a match and moveshi = mid - 1so duplicates are searched to the left;arr[mid] < targetmoveslo = mid + 1. - The replay shows
lo=0, hi=6, mid=3matching4and recordingresult=3, thenlo=0, hi=2, mid=1moving right because2 < 4, thenlo=2, hi=2, mid=2recording the first occurrenceresult=2. console.log(result)prints2. Runtime allocation is limited to the input array and the output formatting; the search itself only updates scalar bindings, so it adds no ongoing GC pressure.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-first`.
cross-language comparison
This JavaScript DSA version keeps the same data and final output as every other DSA book in this wave.