Binary Search Thought Process: 4 Templates

Binary Search can be applied to a problem where we can find a function(if condition of the code) that map elements in left half to True and the other half to False or vice versa . Don't think it is just for the full sorted array (Refer here :https://www.youtube.com/watch?time_continue=67&v=GU7DpgHINWQ&feature=emb_logo)

Now a Binary Search can be solved using 4 Templates: You can try solving all Binary Search questions using just one template.
Example Post : In this example , I have solved a question using all 4 templates : https://leetcode.com/problems/find-peak-element/discuss/788474/general-binary-search-thought-process-4-templates

Templates :

  1. Find the First True:

    T T T T T F F F or F F F F T T T T
    We always try to go the left when finding the First True and the template will be like :

    while left < right :
    	if condition is true:
    		right = mid 
    	else:
    		left = mid +1

    Thought Process for this template : For FFFFTTTT, if mid is second last True , then it is a possible ans but we need to keep searching left because we want First True or minimal True for it . We move to left part by doing right = mid where mid is a potential solution and throw away the right part

  2. Find the Last True:

    T T T T T F F F or F F F F T T T T T

    We always try to go the right when finding the Last True and the template will be like :

    while left < right :
    	if condition is true:
    		left = mid 
    	else:
    		right = mid - 1

    Thought Process for this template : For T T T T T F F F, if mid is First True , then it is a possible ans but we need to keep searching right because we want Last True or Maximal True for it . We move to right half by doing left = mid where mid is a potential solution and throw away the left part

  3. Find the First False:
    T T T T T F F F or F F F F T T T T

    while left < right:
    	if condition is False: 
    		left = mid +1
    	else:
    		right = mid

    Thought Process this template : For T T T T T F F F, if mid is at Last False , then it is a possible ans but we need to keep searching left because we want First False or Minimal False for it .

  4. Find the Last False:
    T T T T T F F F or F F F F F T T T

    while left < right:
    	if condition is False: 
    		right  = mid -1
    	else:
    		left = mid

    Thought Process for this template : For F F F F F T T T , if mid is second False , then it is a possible ans but we need to keep searching right because we want Last False or Maximal False for it .

You have to change the condition in the "if statement" such that the problem is converted to one of the problem above. You can stick to one template if you want like always finding the First true . Now this "condition" in "if statement" can be the one which question is asking or it can be the opposite of it .

Comments (1)