FlareStart
HomeNewsHow ToSources
FlareStart

Where developers start their day. All the tech news & tutorials that matter, in one place.

Quick Links

  • Home
  • News
  • Tutorials
  • Sources
  • Privacy Policy

Connect

© 2026 FlareStart. All rights reserved.

Back to articles
First & Last Occurences
How-ToProgramming Languages

First & Last Occurences

via Dev.to PythonAbirami Prabhakar2h ago

lets first understand the question We are given a sorted array which may contain duplicate elements we are also given a number x, and we need to find: the first occurrence of x the last occurrence of x we return the indices in the form: [first_index, last_index] if the element is not present, return [-1, -1] sample i/p and o/p Input: arr = [1, 3, 5, 5, 5, 5, 67, 123], x = 5 Output: [2, 5] how to approach the solution I first thought → "can I just loop through the array and find first and last?" yes, but that will take O(n) time since the array is already sorted, we can do better using binary search instead of finding just one occurrence, we modify binary search to find the leftmost occurrence and rightmost occurrence it work by running a binary search twice for first occurrence → move left when found for last occurrence → move right when found step by step arr = [1, 3, 5, 5, 5, 5, 67] find first: mid = 5 → found → move left continue until first position → index 2 find last: mid = 5 → f

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles

I Haven’t Written Real Code in 3 Months. My Products Still Ship.
How-To

I Haven’t Written Real Code in 3 Months. My Products Still Ship.

Medium Programming • 3h ago

My Learning Experience with Sorting Algorithms
How-To

My Learning Experience with Sorting Algorithms

Dev.to Tutorial • 5h ago

Stop Building Projects. Start Building Systems.
How-To

Stop Building Projects. Start Building Systems.

Medium Programming • 5h ago

I Learned More in 3 Months Than 3 Years (The System That Actually Works)
How-To

I Learned More in 3 Months Than 3 Years (The System That Actually Works)

Medium Programming • 5h ago

CA 12 - Next Permutation
How-To

CA 12 - Next Permutation

Dev.to • 6h ago

Discover More Articles