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.go
package main
import "fmt"
func main() {
arr := []int{1, 2, 4, 4, 4, 7, 9}
target := 4
lo := 0
hi := len(arr) - 1
result := -1
for lo <= hi {
mid := lo + (hi-lo)/2
if arr[mid] == target {
result = mid
hi = mid - 1
} else if arr[mid] < target {
lo = mid + 1
} else {
hi = mid - 1
}
}
fmt.Println(result)
}
Complexity
- Time: O(log n)
- Space: O(1)
Implementation notes
- Go builds the sorted input with
arr := []int{1, 2, 4, 4, 4, 7, 9}; the search reads from that slice's backing array and never mutates it. lo,hi,mid, andresultareintvalues. The midpoint useslo + (hi-lo)/2, so the trace follows the changing window rather than relying on a library search helper.result := -1is the not-found sentinel. On equality the code recordsresult = midand then setshi = mid - 1, which is why duplicates at indices2,3, and4still return the first index.- The branch order checks equality first, then
arr[mid] < target, otherwise narrowing the high bound. Thefor lo <= higuard keeps each indexed read in range for this input; Go still applies normal slice bounds checks. - The replay records
mid=3as a match (result=3,hi=2), thenmid=1with value2(lo=2), thenmid=2as the leftmost match (result=2,hi=1).fmt.Println(result)prints2.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-first`.
cross-language comparison
This Go DSA version keeps the same data and final output as every other DSA book in this wave.