Binary Search Variations | Algorithm Interview | Skill-Lync Resources
Medium Algorithms Searching Algorithms

How do you find first/last occurrence using binary search?

Answer

For first occurrence: when target found, continue searching left half (right = mid - 1) and track result. For last occurrence: when target found, continue searching right half (left = mid + 1) and track result. Both are O(log n). This technique applies to finding lower/upper bound, count of element, and insertion position. Python's bisect_left/bisect_right and C++'s lower_bound/upper_bound implement these.

Master These Concepts with IIT Certification
IIT Certified

Master These Concepts with IIT Certification

175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.

Relevant for Roles

Software Engineer Backend Developer Algorithm Developer