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
# Finding First and Last Occurrence in a Sorted Array (Java)
NewsTools

# Finding First and Last Occurrence in a Sorted Array (Java)

via Dev.to TutorialSharmila devi4h ago

When working with sorted arrays, one common problem is to find the first and last occurrence of a given element. This becomes especially interesting when the array contains duplicate values . In this blog, we’ll walk through an efficient approach using Binary Search and implement it in Java. 🚀 Problem Statement Given a sorted array arr[] (possibly with duplicates) and a number x , find: The first occurrence of x The last occurrence of x 👉 Example Input : arr = [ 1 , 2 , 2 , 2 , 3 , 4 , 5 ] x = 2 Output : [ 1 , 3 ] If x is not present, return: [ - 1 , - 1 ] 💡 Key Idea A normal binary search finds any one occurrence of x . But here, we need the extreme positions : First occurrence → keep searching on the left side Last occurrence → keep searching on the right side So, we modify binary search slightly and run it twice . ⚡ Approach 1. Find First Occurrence If arr[mid] == x , store index and move left Continue searching in the left half 2. Find Last Occurrence If arr[mid] == x , store index

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
0 views

Related Articles

News

Structuring Go projects

Lobsters • 47m ago

The Code Simplification Skill Senior Engineers Develop
News

The Code Simplification Skill Senior Engineers Develop

Medium Programming • 1h ago

These Sony headphones are under $50 and punch above their weight - and they're on sale
News

These Sony headphones are under $50 and punch above their weight - and they're on sale

ZDNet • 1h ago

Copilot Didn’t Replace Developers But Replaced Thinking
News

Copilot Didn’t Replace Developers But Replaced Thinking

Medium Programming • 1h ago

Google TV’s new Gemini features keep fans updated on sports teams and more
News

Google TV’s new Gemini features keep fans updated on sports teams and more

TechCrunch • 1h ago

Discover More Articles