a typical bs but if target is bigger than what elements we have in our list, we need to give the index +1 as answer. I didnt and I just returend left for any cases so I got that as error
class Solution {
public int searchInsert(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int mid = left + (right-left)/2;
if (arr[mid] == target) {
return mid; // found
} else if (arr[mid] < target) {
left = mid + 1; // search right
} else {
right = mid; // search left
}
}
return (arr[left] < target) ? left + 1 : left;
}
}
log n time
1 space