Fetching latest headlinesโ€ฆ
CA 19 - First & Last Occurences
NORTH AMERICA
๐Ÿ‡บ๐Ÿ‡ธ United Statesโ€ขMarch 22, 2026

CA 19 - First & Last Occurences

0 views0 likes0 comments
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

Comments (0)

Sign in to join the discussion

Be the first to comment!