Find first and last position of element in sorted array - https://webrewrite.com/find-first-and...
First and Last Occurrences of x in sorted array where x is a target value
Given a sorted array of integers (Sorted in ascending order). Write a code to find first and last position of a given number. If a number is not found return -1.
The array is sorted and it contains duplicate elements.
In this tutorial, I have explained java code to find first and last position of element in a sorted array using Binary Search in O(logn) time complexity.
For Example -
Example 1 -
Input : {1, 4, 7, 8, 8, 11, 11, 11, 11, 12, 13, 13}, target = 11
Output: {5, 8}
First position : 5
Last position : 8
Example 2 -
Input : {1, 6, 7, 7, 8, 8, 9, 9}, target = 5
Output: {-1, -1}
The target value is not found in an array.
NOTE - Try to solve this problem in O(logn) time complexity.