I\'m trying to understand how do I modify the binary search for it work for first and last occurrences, surely I can find some code on the web but I\'m trying to reach deep
You could run binary search to find any arbitrary occurrence (if it exists) of the key in the array.
Next, the first occurrence would be to the left of the index returned, so you set the bounds accordingly and run binary search repeatedly until the element to the left of the index is not equal to the key. Proceed similarly for the last occurrence
binary_search(0, n-1, key)
{
/* run binary search, get index of key */
leftmost=min(leftmost, index)
if (array[index-1]==key and leftmost==index)
binary_search(0, index-1, key)
rightmost=max(rightmost, index)
if (array[index+1]==key and rightmost==index)
binary_search(index+1, n-1, key)
}