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
Watch video Find First and Last Occurrences of an Element in a Sorted Array Using Binary Search | Java DSA Guide online without registration, duration hours minute second in high quality. This video was added by user RAHUL VIJAYAN 31 January 2025, don't forget to share it with your friends and acquaintances, it has been viewed on our site 34 once and liked it 6 people.