binary search
algorithm
first occurrence
data structures
coding techniques

First occurrence in a binary search

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In computer science, finding the first occurrence of an element in a sorted array is a common problem, particularly when dealing with large datasets where efficiency is key. Binary Search, with its logarithmic time complexity, presents an optimal solution for this problem. This article delves into the technical nuances of using binary search to find the first occurrence of an element in a sorted array, supported by examples and explanations.

Binary Search Basics

Binary Search is a divide-and-conquer algorithm used to find the position of a target value within a sorted array. The basic idea is to repeatedly divide the search interval in half, reducing the size of the problem with each step. If the target value is smaller than the middle element of the interval, the search continues in the left subarray, otherwise, it proceeds in the right subarray. The algorithm assumes random access to the elements for efficient mid-point evaluation, yielding a time complexity of O(logn)O(\log n).

Finding the First Occurrence

To find the first occurrence of a target element in a sorted array, slight modifications are made to the standard binary search algorithm. The key difference is in handling cases where the middle element equals the target element. Instead of returning the mid-point immediately, the algorithm checks if this is the first occurrence by verifying the element preceding it.

Algorithm Steps

  1. Initialization: Set `low` to 0 and `high` to the length of the array minus one.
  2. Midpoint Calculation: While `low` is less than or equal to `high`, calculate the midpoint `mid` using: mid=low+(highlow)2\text{mid} = \text{low} + \frac{(\text{high} - \text{low})}{2}
  3. Comparison and Search:
    • If the array at `mid` equals the target and `mid` is 0 or the preceding element is not the target, return `mid` as the first occurrence.
    • If the array at `mid` is greater than or equal to the target, shift `high` to `(mid - 1)` to continue the search to the left.
    • Otherwise, set `low` to `(mid + 1)` to continue the search to the right.
  4. End Condition: If the loop exits without returning, the target is not in the array, indicating no occurrence.

Example

Consider the sorted array `[2, 4, 10, 10, 10, 18, 20]` and a target of `10`.

  • Initialize: `low = 0`, `high = 6`
  • First Iteration: `mid = 3` (element is 10), move `high = 2` (since we need the first occurrence)
  • Second Iteration: `mid = 1`, move `low = 2`
  • Third Iteration: `mid = 2` (element is 10 and the first occurrence), end loop

By following this approach, the first occurrence of `10` is found at index `2`.

Considerations and Limitations

  • Duplicated Elements: The primary use of this algorithm is in arrays with repeated elements, as standard binary search only identifies the presence, not the exact occurrence.
  • Complexity: Time complexity remains O(logn)O(\log n) due to the exclusion of half of the elements in each iteration.
  • Sorted Data: The algorithm assumes that the input array is sorted. For unsorted data, sorting must be done prior, which would alter the overall complexity.

Summary Table

AspectDetails
Use CaseFinding first occurrence in a sorted array
Algorithm UsedModified Binary Search
Time ComplexityO(logn)O(\log n)
Key ModificationContinue search left when finding target until the first occurrence
Data RequirementSorted Array
Optimal ForLarge datasets with repeated elements

Additional Subtopics

Recursive Approach

While the iterative method is commonly used for its simplicity, a recursive approach can also be implemented for binary search. The recursive method follows a similar logic, with each call handling a subarray, reducing just like the loop in the iterative approach, until the base condition is met.

Practical Applications

  • Databases: Efficient querying, especially when querying indexes with duplicate entries.
  • Statistics: Used in algorithms that require frequency analysis of sorted data.

Conclusion

Finding the first occurrence of an element using binary search is a fundamental problem with practical relevance across various fields. Understanding and implementing this algorithm effectively allows developers and engineers to work efficiently with large datasets, taking full advantage of the logarithmic search time offered by binary search.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.