download

Binary search with duplicates: how do you find the first match?

Algorithms~15 minReviewed 29 Oct 2026Free · No sign-in

Question

Write first_at_least(values, target). The list values is sorted in ascending order and may contain duplicates. Return the index of the first value that is greater than or equal to target. If no value is big enough, return len(values). Use binary search, so it runs in O(log n).

"PYTHON"
values = [3, 7, 7, 12, 18]
first_at_least(values, 7)   # 1, the first 7
first_at_least(values, 8)   # 3, the 12
first_at_least(values, 20)  # 5, nothing is big enough
first_at_least([], 5)       # 0
"CODE · PYTHON"
def first_at_least(values, target):
    ...
Show hints (3)
  1. "DON'T STOP EARLY"

    Finding a 7 is not enough. In [7, 7, 7] the middle 7 is a match, but not the first one. When you find a match, keep searching to the left.

  2. "TWO INDEXES"

    Use lo = 0 and hi = len(values). Keep two facts true as you go: everything before lo is too small, and everything from hi on is big enough. Stop when lo == hi.

  3. "HOW TO MOVE"

    If values[mid] < target, the answer is to the right: set lo = mid + 1. Otherwise mid itself may be the answer, so set hi = mid, not mid - 1.

Show checked explanation

Search a range from lo to hi, starting with the whole list, and halve it each step. If the middle value is too small, set lo = mid + 1. Otherwise set hi = mid, because the middle may be the first match. When lo == hi, that index is the answer. It equals len(values) when nothing is big enough.

"SOLUTION · PYTHON"
def first_at_least(values, target):
    lo, hi = 0, len(values)
    while lo < hi:
        mid = (lo + hi) // 2
        if values[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo


values = [3, 7, 7, 12, 18]
for target in (7, 8, 20):
    print(target, first_at_least(values, target))
print("empty", first_at_least([], 5))
"OUTPUT"
7 1
8 3
20 5
empty 0

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Here is the search for 7 in [3, 7, 7, 12, 18]. The range runs from lo to hi, and hi itself is not included.

steplohimidvalues[mid]move
105277 is not below 7, so hi = 2
202177 is not below 7, so hi = 1
301033 is below 7, so lo = 1

Now lo == hi == 1, so the answer is 1.

Step 1 found a 7 at index 2 but kept going, because an earlier 7 was still possible. Index 1 holds one. With hi = 2, index 2 stays the answer unless the search finds an earlier match.

Why does it work? Two facts stay true on every step. Everything before lo is below the target. Everything from hi on is big enough. Each step makes the range shorter, so the loop ends. When lo == hi, nothing is left between them, so lo is exactly where the small values end.

For target 20, every value is too small, so lo moves right until it reaches 5, which is len(values). For an empty list the loop never runs, and the answer is 0. Neither is a valid index. They are the places where you could insert the target and keep the list sorted. To test for an exact match, take i = first_at_least(values, target) and check i < len(values) and values[i] == target.

Each step halves the range, so a list of 1,000,000 items needs at most 20 steps.

Common mistakes

  • Returning mid as soon as values[mid] == target. With duplicates you get a match, but not always the first one. In [7, 7, 7] that returns index 1 instead of 0.
  • Writing lo = mid instead of lo = mid + 1. When one item is left, mid equals lo. If that item is too small, lo never moves, and the loop runs forever.
  • Starting with hi = len(values) - 1. Then the answer can never be len(values). A target of 20 returns 4, the index of 18, instead of 5.
  • Reading values[i] right away. When nothing is big enough, i equals len(values), and values[i] raises IndexError.

Follow-up questions

  • "How many values in [2, 2, 6, 9, 9, 14] are from 6 to 9, inclusive?" Run two searches and subtract. The first value that is at least 6 is at index 2. The first value greater than 9 is at index 5. For that second search, change < to <=, so a value equal to 9 sends the search right. The count is 5 - 2 = 3: the values 6, 9 and 9.
  • "Is there something in the standard library for this?" Yes. bisect.bisect_left(values, target) returns the same index, and bisect.bisect_right is the "first value greater than" version. bisect.insort adds an item and keeps the list sorted. Its search is O(log n), but inserting into a list shifts the items after it, so the whole call is O(n).
  • "What if the list is not sorted?" Then the index means nothing, and binary search won't warn you. Checking the order first costs O(n), which removes the speed gain. Keep the list sorted where you build or update it, and don't change it during a search.

What a strong answer covers

Says what to return before coding, including len(values) when nothing fits. Explains why it is hi = mid but lo = mid + 1. Tests duplicates, an empty list and a target past the end. Mentions bisect_left.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from The Python Interview Handbook (Nezir Zahirovic, 2023); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.