Geeksforgeeks

It's live! The biggest programming festival has begun! Check out Geek Week now!

Error

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 ≤ 10^{7}

We are replacing the old Disqus forum with the new Discussions section given below.

Click here to view old Disqus comments.

Click here to view old Disqus comments.

Login to report an issue on this page.

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

YesLoading...

First and last occurrences of x

...