Problem of the day
You have been given a sorted array/list 'arr' consisting of ‘n’ elements. You are also given an integer ‘k’.
Now, your task is to find the first and last occurrence of ‘k’ in 'arr'.
1. If ‘k’ is not present in the array, then the first and the last occurrence will be -1.
2. 'arr' may contain duplicate elements.
Input: 'arr' = [0,1,1,5] , 'k' = 1
Output: 1 2
Explanation:
If 'arr' = [0, 1, 1, 5] and 'k' = 1, then the first and last occurrence of 1 will be 1(0 - indexed) and 2.
The first line of each test case contains two single-space separated integers ‘n’ and ‘k’, respectively.
The second line of each test case contains ‘n’ single space-separated integers denoting the elements of the array/list 'arr'.
Return two single-space separated integers denoting the first and the last occurrence of ‘k’ in 'arr', respectively.
You do not need to print anything; it has already been taken care of. Just implement the given function.
8 2
0 0 1 1 2 2 2 2
4 7
For this testcase the first occurrence of 2 in at index 4 and last occurrence is at index 7.
4 2
1 3 3 5
-1 -1
Try to do this in O(log(n)).
1 <= n <= 10^5
0 <= k <= 10^9
0 <= arr[i] <= 10^9
Time Limit : 1 second
Brute force the problem by traversing the array.
Naively traverse the array and find the first and last occurrence of ‘K’ in ARR.
O(N), where N is the length of the given array/list ARR.
We are iterating over the array/list ARR once. Hence, the time complexity is O(N).
O(1), i.e. constant space complexity.