Find First and Last Occurrences of an Element in a Sorted Array Using Binary Search | Java DSA Guide

Опубликовано: 31 Январь 2025
на канале: RAHUL VIJAYAN
34
6

In this video, we tackle an important Data Structures and Algorithms (DSA) problem: Finding the First and Last Occurrences of an Element in a Sorted Array. Using Binary Search, we achieve an optimized O(log N) solution instead of a brute-force O(N) approach.

Problem Statement:
Given a sorted array with possible duplicate elements, we need to find the first and last occurrence of a given number x. If x is not found, return [-1, -1].

Example Test Case:
Input:
arr[] = [1, 3, 5, 5, 5, 5, 67, 123, 125], x = 5
Output:
[2, 5]

Explanation:
First occurrence of 5 is at index 2
Last occurrence of 5 is at index 5

Approach:
We will use two binary searches:
1️⃣ First Occurrence Search – Move left to find the first index of x.
2️⃣ Last Occurrence Search – Move right to find the last index of x.

Time Complexity Analysis:
First Occurrence: O(log N)
Last Occurrence: O(log N)
Total Complexity: O(2 * log N) ≈ O(log N)
This Java implementation ensures optimal performance compared to a naive linear search (O(N)).

Topics Covered:
✅ Binary Search Implementation
✅ Efficient Searching in Sorted Arrays
✅ Optimized Java DSA Coding Approach
✅ Handling Edge Cases in Interview Problems

📌 Whether you're preparing for FAANG interviews or enhancing your DSA skills, this problem is crucial. Watch the full explanation with detailed code walkthrough and dry run.

LeetCode DSA Playlist:    • Crack LeetCode Using Java  

GeeksforGeeks DSA Playlist:    • GeeksforGeeks DSA Solutions in Java |...  

Wings 1:    • Wings 1  

Let’s grow together! I’m open to collaborations and new ideas. Connect with me on:
🌐 LinkedIn:   / rahul-vijayan-682a12194  
🐦 Profile: https://rahulvijayan.in/
📸 Instagram:   / rv_official_yt  
🌟 GitHub: https://github.com/Rahulvijayan2291/
💡LeetCode: https://leetcode.com/u/rahulvijayan2291/

🔥 Don't forget to Like, Comment, and Subscribe for more DSA tutorials! 🚀

binary search, java dsa, first and last occurrence, sorted array search, java coding interview, faang interview question, dsa binary search, java programming, coding for interviews, efficient search algorithm, data structures, algorithms in java, find element in array, competitive programming


Смотрите видео Find First and Last Occurrences of an Element in a Sorted Array Using Binary Search | Java DSA Guide онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь RAHUL VIJAYAN 31 Январь 2025, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 34 раз и оно понравилось 6 людям.