...

/

First and Last Occurrence of an Element

First and Last Occurrence of an Element

Use Binary Search to find the first and last occurrence of an element in an array.

Problem statement

Given a sorted array with possibly duplicate elements, the task is to find indexes of the first and last occurrences of an element x in the given array.

For example, we have input arr[] = {1, 3, 5, 5, 5, 5, 67, 123, 125} and x = 5. The first occurrence is at index 2 and last occurrence is at index 5.

Let us look at another example. We have input arr[] = {1, 3, ...