Search
Search One Element in Sorted Array (when we know the element)
Binary Search
Example questions:
852_ Peak Index in a Mountain Array
Search One element in an Array (When we don't know the element, but know it's property, ie. kth largest, median)
Use the idea of quick sort
Example questions:
215_Kth Largest Element in an Array
Search Two Elements in Sorted Array
Two passes of binary search
Example questions:
34_Find First and Last Position of Element in Sorted Array
Two pointer
Search in Rotated Sorted Array
Binary search. Identify the part that is not rotated by comparing the values on the left and right.
Example questions:
33_Search in Rotated Sorted Array
153_Find Minimum in Rotated Sorted Array
Search for more than two elements
convert to search for two elements
Search in Unsorted Array
we can sort first
usually use dictionary to keep corresponding information
Use Math Properties
Use the property of sum, average, etc.
Example questions:
268_Missing Number
Bit Manipulation
Notes for search:
Sorted array with distinct elements or with duplicates could make a huge difference in search algorithm. Many times if all elements are distinct, we can find algorithm in such as binary search. If duplicates exists, it may be hard to avoid algorithm.
Binary Search Template
For assigning new M, use M = L + (R-L)//2 instead of M = (L + R)//2 to avoid overflow. The overflow may happen if L and R are larger than the largest possible integers in the system. Refer to this post for details.
Reminder:
Sometimes when we use binary search, we don't need to test the equal sign. We can jus throw away the left part or right part. In this case, we will update index as L = M or R = M.
Last updated