First and Last Position of an Element In Sorted Array

Easy
0/40
Average time to solve is 15m
804 upvotes
Asked in companies
AmazonMicrosoftAdobe

Problem statement

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'.


Note :
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.


Example:
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.


Detailed explanation ( Input/output format, Notes, Images )
Input Format
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'.


Output Format :
Return two single-space separated integers denoting the first and the last occurrence of ‘k’ in 'arr', respectively.


Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Sample Input 1:
8 2
0 0 1 1 2 2 2 2


Sample output 1:
4 7


Explanation of Sample output 1:
For this testcase the first occurrence of 2 in at index 4 and last occurrence is at index 7.


Sample Input 2:
4 2
1 3 3 5


Sample output 2:
-1 -1


Expected Time Complexity:
Try to do this in O(log(n)).


Constraints:
1 <= n <= 10^5
0 <= k <= 10^9
0 <= arr[i] <= 10^9

Time Limit : 1 second
Hint

Brute force the problem by traversing the array.

Approaches (2)
Naive Approach

Naively traverse the array and find the first and last occurrence of ‘K’ in ARR.

Time Complexity

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).

Space Complexity

O(1), i.e. constant space complexity. 

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
First and Last Position of an Element In Sorted Array
Full screen
Console