Searching Flashcards
Binary Search mid split
Remember to split into BS(left,mid-1) and BS(mid+1,right) since the base check already checks if arr[mid] == key.
Find Majority Element
To find majority, first find a candidate for majority by Moore’s Voting Algorithm.
- Set index=0 and count=1 and check if A[i] == A[idx]
- if true, then increase count else decrease.
- If count becomes 0, then set idx = i and count=1
Finally, check if the candidate is indeed the majority element. if count > N//2: return A[idx]
Peak element in sorted rotated array
[10 20 30 40 1 2]
Apply binary search. Check A[mid] wrt any corner element. If A[mid] > A[left] then pivot lies on right and vice-versa.
Peak element in unsorted array
[10 20 15 5 23 90 67]
A corner element is also a peak if it is larger than its neighboring element.
Apply binary search. compare mid wrt its left and right.
If left or right is greater than move towards the greater side since peak element will lie in that direction. If both are greater, then peak lies in both direction. In that case, you may pick either.
Search key in an infinite sorted array
Binary search. First find the right index to work with by search from i=1 while(A[i] < key): i=i*2. (Check A[0] == key).
check if A[i] == key return i.
Then you can apply binary search between i/2 to i.
Find Square Root
if not perfect square return floor of sqrt. eg 5 -> 2. To find sqrt of x:
mid = l + (r-l)//2
sqrt = x//mid
if mid == sqrt or (mid < sqrt and ((mid+1) > x//(mid+1))):
return mid