Skip to content

Commit bd2cf9b

Browse files
committed
Variant of Binary Search to find low and High indices of a repeating number
1 parent 4fddd94 commit bd2cf9b

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

arrays/findHighLowIndex.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Given a sorted array,find the low and high index of a number.
3+
Return -1 if the element is not found
4+
Array length can be large with a lot of duplicates
5+
*/
6+
7+
package main
8+
9+
import ("fmt"
10+
)
11+
12+
// We can use binarySearch to solve this problem easily
13+
func findLowIndex(arr []int,searchNum int) int {
14+
startIdx := 0
15+
endIdx := len(arr) -1
16+
mid := startIdx + (endIdx - startIdx)/2
17+
for (startIdx <= endIdx) {
18+
if arr[mid] < searchNum {
19+
startIdx = mid+1
20+
} else {
21+
endIdx = mid-1
22+
}
23+
mid = startIdx + (endIdx - startIdx)/2
24+
}
25+
if arr[startIdx] == searchNum {
26+
return startIdx
27+
}
28+
return -1
29+
}
30+
31+
func findHighIndex(arr []int,searchNum int) int {
32+
startIdx := 0
33+
endIdx := len(arr) -1
34+
mid := startIdx + (endIdx - startIdx)/2
35+
for (startIdx <= endIdx) {
36+
if arr[mid] > searchNum {
37+
endIdx = mid-1
38+
} else {
39+
startIdx = mid+1
40+
}
41+
mid = startIdx + (endIdx - startIdx)/2
42+
}
43+
if arr[endIdx] == searchNum {
44+
return endIdx
45+
}
46+
return -1
47+
}
48+
49+
50+
func main() {
51+
arr := []int{1,2,5,5,5,5,5,5,5,5,20}
52+
searchNum := 5
53+
low := findLowIndex(arr,searchNum)
54+
high := findHighIndex(arr,searchNum)
55+
fmt.Println("Indices of number:",searchNum,"Low:",low,"High:",high)
56+
}

0 commit comments

Comments
 (0)