2nd post try, now with func feasible that is only a check
func feasible(arr[]int, idx int, target int) bool {
if arr[idx] == target {
return true
}
return false
}
func findFirstOccurrence(arr []int, target int) int {
left := 0
right := len(arr) - 1
idx := -1
for left <= right {
mid := left + (right - left) / 2
if feasible(arr, mid, target) {
idx = mid
}
if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return idx
You can use the classic solution with a little bit of an extra test at the end:
public static int findFirstOccurrence(List<Integer> arr, int target) {
int left = 0 ;
int right = arr.size() - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr.get(mid) >= target) {
result = mid;
right = mid - 1;
}
else
left = mid + 1;
}
return result != -1 && arr.get(result) == target ? result : -1;
}
function firstNotSmaller(arr, target) {
let left = 0,
right = arr.length - 1,
firstIndex = -1
while(left <= right){
let mid = left + Math.floor((right - left) / 2);
if(arr[mid] >= target){
right = mid-1;
}else{
left = mid+1;
}
}
return left
}
It looks like the template for this (shown by the template button under the input box for the problem) is linked to the backtracking templates which doesn’t seem correct here