
Originally published byDev.to
1.Problem Understanding
Given sorted array we need to find the first occurance and last occurance of the duplicates
if not found โ return [-1, -1]
Example
arr = [1, 3, 5, 5, 5, 67, 123]
x = 5
Output:
[2, 4]
2.Idea
One for first occurrence
One for last occurrence
First Occurrence:
When you find x
donโt stop
move LEFT to find earlier occurrence
Last Occurrence:
When you find x
donโt stop
move RIGHT to find later occurrence
3.Example
Array:
[1, 3, 5, 5, 5, 67]
Searching for 5
First occurrence:
Keep going LEFT
Last occurrence:
Keep going RIGHT
4.Algorithm
First Occurrence:
If arr[mid] == x
โ store index
โ move right = mid - 1
Last Occurrence:
If arr[mid] == x
โ store index
โ move left = mid + 1
๐บ๐ธ
More news from United StatesUnited States
NORTH AMERICA


