Given a sorted integer array, find the index of a given number’s first or last occurrence. If the element is not present in the array, report that as well.

For example,

Input:
 
nums = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9]
target = 5
 
Output:
 
The first occurrence of element 5 is located at index 1
The last occurrence of element 5 is located at index 3
 
 
Input:
 
nums = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9]
target = 4
 
Output:
 
Element not found in the array

Practice this problem

A simple solution would be to run a linear search on the array and return the given element’s first or last occurrence. The problem with this approach is that its worst-case time complexity is O(n), where n is the size of the input. This solution also does not take advantage of the fact that the input is sorted. We can easily solve this problem in O(log(n)) time by modifying the binary search algorithm.

Finding first occurrence of the element

The standard binary search terminates as soon as any occurrence of the given target element is found. To find the given element’s first occurrence, modify the binary search to continue searching even on finding the target element. Instead, update the result to mid and search towards the left (towards lower indices), i.e., modify our search space by adjusting high to mid-1 on finding the target at mid-index.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

The first occurrence of element 5 is located at index 1

Java


Download  Run Code

Output:

The first occurrence of element 5 is located at index 1

Python


Download  Run Code

Output:

The first occurrence of element 5 is located at index 1

Finding last occurrence of the element

To find the element’s last occurrence, modify the standard binary search to continue searching even on finding the target. Instead, update the result to mid and go on searching towards the right (towards higher indices), i.e., modify our search space by adjusting low to mid+1 on finding the target at mid-index.

Following is the C, Java, and Python implementation based on the above idea:

C


Download  Run Code

Output:

The last occurrence of element 5 is located at index 3

Java


Download  Run Code

Output:

The last occurrence of element 5 is located at index 3

Python


Download  Run Code

Output:

The last occurrence of element 5 is located at index 3

The time complexity of the above solutions is O(log(n)) and doesn’t require any extra space.

 
Exercise:

1. Write a recursive version of the above solutions.

2. Check if the given integer appears more than n/2 times in a sorted array.