
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
Related News
Jeff Bezos Seeking $100 Billion to Buy Manufacturing Companies, 'Transform' Them With AI
5h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
5h ago
Microsoft Says It Is Fixing Windows 11
5h ago
NASA's Hubble Unexpectedly Catches Comet Breaking Up
5h ago
Intel, NVIDIA, AMD GPU Drivers Finally Play Nice With ReactOS
5h ago


