Back to articles
First & Last Occurences

First & Last Occurences

via Dev.to TutorialJeyaprasad R

In this task, I worked on finding the first and last positions of a given number in a sorted array. Instead of scanning the entire array, I used binary search to do it efficiently. What I Did I created three functions: first_occurrence() → finds the first position of the element last_occurrence() → finds the last position of the element find_positions() → combines both results How I Solved It I used binary search twice, with a small twist: 1. Finding First Occurrence If I find the target, I store the index Then I continue searching on the left side (because there might be an earlier occurrence) 2. Finding Last Occurrence If I find the target, I store the index Then I continue searching on the right side (because there might be a later occurrence) Key Idea Move left (high = mid - 1) → to find first occurrence Move right (low = mid + 1) → to find last occurrence Code python id = " xkqptm " def first_occurrence ( arr , x ): low , high = 0 , len ( arr ) - 1 ans = - 1 while low <= high : mi

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles