New update is available. Click here to update.
sidenav-btnClose
Topic list
First and Last Position of an Element In Sorted Array
EASY
15 mins
326 upvotes
Binary Search
Arrays
Topics (Covered in this problem)
Problem solved
Skill meter
Binary Search
-
Arrays
-
Other topics
Problem solved
Skill meter
Strings
-
Matrices (2D Arrays)
-
Sorting
-
Linked List
-
Stacks & Queues
-
Trees
-
Graph
-
Dynamic Programming
-
Greedy
-
Tries
-
Binary Search Trees
-
Heap
-
Bit Manipulation
-

First and Last Position of an Element In Sorted Array

Easy
Avg time to solve 15 mins
Success Rate 85 %
Share
326 upvotes

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.

For example, 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, Constraints, Images )
Sample Input 1:
2
6 3
0 5 5 6 6 6
8 2
0 0 1 1 2 2 2 2
Sample output 1:
-1 -1 
4 7
Explanation of Sample output 1:
For the first test case, 3 is not present in the array. Hence the first and last occurrence of 3 is -1 and -1.

For the second test case, the first occurrence of 2 in at index 4 and last occurrence is at index 7.
Sample Input 2:
2
4 0
0 0 0 0
1 2
2
Sample output 2:
0 3
0 0
Reset Code
Full screen
copy-code
Console