Leaderboard
Showing:
Handle Score
@Ibrahim Nash 6420
@blackshadows 6376
@mb1973 5604
@Quandray 5231
@akhayrutdinov 5111
@saiujwal13083 4510
@sanjay05 3762
@kirtidee18 3673
@marius_valentin_dragoi 3522
@sushant_a 3459
@verma_ji 3413
Complete Leaderboard
First and last occurrences of x
Basic Accuracy: 65.97% Submissions: 5823 Points: 1

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

Example 1:

Input:
n=9, x=5
arr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }
Output:  2 5
Explanation: First occurrence of 5 is at index 2 and last
             occurrence of 5 is at index 5. 

 

Example 2:

Input:
n=9, x=7
arr[] = { 1, 3, 5, 5, 5, 5, 7, 123, 125 }
Output:  6 6 

Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function find() that takes array arr, integer n and integer x as parameters and returns the required answer.
Note: If the number x is not found in the array just return both index as -1.

 

Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1).

 

Constraints:
1 ≤ N ≤ 107

 

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

First and last occurrences of x

Output Window