 # Stuck at condition function in template

Hello Folks, i am learning this concept and template of BS, while occuring given leetcode problem , i am confuse with conition function hear i am giving my code, it is working but i have made changes in template slightly i.e. return low instead of -1, but if we approch this problem with given template than can you suggest me condition function or give a hint,approch or whatever it is, Thanks in Advance

```````class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
def bsearch(l,h,check):
while l <= h :
m = (l + h) // 2
result = check(m)
if result == 'found':
return m
elif result == 'left':
h = m - 1
else:
l = m + 1
return l

def check(mid):
val = nums[mid]
if val == target:
return 'found'
elif val < target:
return 'right'
else:
return 'left'

return bsearch(0,len(nums)-1,check)`
``````

Example 1:

Input: nums = [1,3,5,6], target = 5 Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2 Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7 Output: 4

Example 4:

Input: nums = [1,3,5,6], target = 0 Output: 0

Example 5:

Input: nums = , target = 0 Output: 0

I did not get your question, Can you please explain it more clearly.

return h+1, when loop breaks.
Because if the target is not in the list ‘h’ will end up at target -1 position and while loop will break.
Therefore h+1 would give the position of the target.

1 Like