package main import "fmt" func countOccurrences(arr []int, x int) int { left, right := 0, len(arr)-1 first, last := -1, -1 // Find first occurrence for left <= right { mid := (left + right) / 2 if arr[mid] == x { first = mid right = mid - 1 } else if arr[mid] < x { left = mid + 1 } else { right = mid - 1 } } if first == -1 { return 0 } left, right = 0, len(arr)-1 // Find last occurrence for left <= right { mid := (left + right) / 2 if arr[mid] == x { last = mid left = mid + 1 } else if arr[mid] < x { left = mid + 1 } else { right = mid - 1 } } return last - first + 1 } func main() { arr := []int{1, 2, 3, 3, 3, 4, 5} fmt.Println(countOccurrences(arr, 3)) }
The number 3 appears three times consecutively at indices 2, 3, and 4. The code finds the first and last occurrence indices and returns their difference plus one.
The two binary searches locate the first and last occurrence of the element, allowing calculation of total occurrences by subtracting indices.
package main import "fmt" func countOccurrences(arr []int, x int) int { left, right := 0, len(arr)-1 first := -1 // Find first occurrence for left <= right { mid := (left + right) / 2 if arr[mid] == x { first = mid left = mid + 1 // Incorrect update } else if arr[mid] < x { left = mid + 1 } else { right = mid - 1 } } if first == -1 { return 0 } return 1 } func main() { arr := []int{1, 2, 3, 3, 3, 4, 5} fmt.Println(countOccurrences(arr, 3)) }
The code incorrectly updates 'left' when finding the first occurrence, causing it to find the last occurrence instead. Also, it returns 1 instead of the count.
package main import "fmt" func countOccurrences(arr []int, x int) int { left, right := 0, len(arr)-1 first, last := -1, -1 for left <= right { mid := (left + right) / 2 if arr[mid] == x { first = mid right = mid - 1 } else if arr[mid] < x { left = mid + 1 } else { right = mid - 1 } } if first == -1 { return 0 } left, right = 0, len(arr)-1 for left <= right { mid := (left + right) / 2 if arr[mid] == x { last = mid left = mid + 1 } else if arr[mid] < x { left = mid + 1 } else { right = mid - 1 } } return last - first + 1 } func main() { arr := []int{1, 2, 3, 3, 3, 4, 5} fmt.Println(countOccurrences(arr, 6)) }
The element 6 is not in the array, so the first occurrence index remains -1 and the function returns 0.
Each binary search runs in O(log n) time, and since two binary searches are performed, the total time complexity remains O(log n).
