Binary Search for First and Last Position in Sorted Array

Day 4/100 – LeetCode Challenge Problem Solved: Find First and Last Position of Element in Sorted Array (34) Today I worked on a problem that requires finding the starting and ending index of a target value in a sorted array. If the target is not present, the result should be [-1, -1]. The important constraint is that the solution must run in O(log n) time. Since the array is sorted, this naturally points to Binary Search. Instead of performing a simple search, the idea is to perform two modified binary searches: One to find the first occurrence of the target, and another to find the last occurrence. By carefully adjusting the search boundaries when the target is found, we can narrow down the exact range. This ensures: The algorithm maintains logarithmic time complexity. The solution handles duplicates correctly. Edge cases such as the target not being present are properly addressed. Time Complexity: O(log n) Space Complexity: O(1) Key takeaway: Binary search is not just about finding whether an element exists. With small boundary modifications, it can be adapted to solve range-based problems efficiently. Understanding how to tweak the search condition is more important than memorizing the template. Day 4 completed. Continuing to sharpen problem-solving fundamentals. #100DaysOfLeetCode #BinarySearch #Java #DataStructures #ProblemSolving #Consistency

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories