intermediate · binary search · lower bound · sorted array

Where does a value start and end?

Problem

A sorted list of exam scores may contain repeats. For a score, return the first and last positions where it appears, or [−1, −1] if it does not appear. Use O(log n) comparisons.

Constraints

  • 0 ≤ n ≤ 32, sorted ascending
  • scores and the target from −999 to 999

Examples

scores = [50, 70, 70, 70, 85], target = 70 → [1, 3]

scores = [50, 85], target = 60 → [−1, −1]

Show the solution

Two lower bounds

lowerBound(x) = first index whose value ≥ x. The run of target values is [lowerBound(target), lowerBound(target + 1)).

Why it is correct

Values below the run are < target and values from lowerBound(target + 1) on are ≥ target + 1, i.e. > target (integers). If lowerBound(target) is past the end or holds another value, target is absent.

Complexity

Time O(log n), extra space O(1). Two binary searches, each at most ⌊log₂ n⌋ + 1 iterations.

Edge cases

  • Empty list.
  • Target smaller or larger than all values.
  • Every value equal to the target.

Common mistakes

  • Finding one match with classic binary search and scanning outwards: O(n) in the worst case.
  • target + 1 overflowing for the maximum integer (impossible within these constraints; use an upper-bound search instead in general).

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class FirstLastOccurrence
{
    /// <summary>First and last positions of target in an ascending array, or (-1, -1). O(log n).</summary>
    public static (int First, int Last) Find(int[] scores, int target)
    {
        int first = LowerBound(scores, target);
        if (first == scores.Length || scores[first] != target)
            return (-1, -1);
        int last = LowerBound(scores, target + 1) - 1;
        return (first, last);
    }
 
    /// <summary>The first index whose value is at least x (scores.Length if none).</summary>
    private static int LowerBound(int[] scores, int x)
    {
        int lo = 0, hi = scores.Length;
        while (lo < hi)
        {
            int mid = lo + (hi - lo) / 2;
            if (scores[mid] < x)
                lo = mid + 1;
            else
                hi = mid;
        }
        return lo;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/FirstLastOccurrence.cs

from collections.abc import Sequence
 
 
def find(scores: Sequence[int], target: int) -> tuple[int, int]:
    """First and last positions of target in an ascending list, or (-1, -1). O(log n)."""
    first = _lower_bound(scores, target)
    if first == len(scores) or scores[first] != target:
        return -1, -1
    last = _lower_bound(scores, target + 1) - 1
    return first, last
 
 
def _lower_bound(scores: Sequence[int], x: int) -> int:
    """The first index whose value is >= x (len(scores) if none); bisect.bisect_left does the same."""
    lo, hi = 0, len(scores)
    while lo < hi:
        mid = (lo + hi) // 2
        if scores[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/first_last_occurrence.py

package dev.bekadan.dsa.problems;
 
public final class FirstLastOccurrence {
    private FirstLastOccurrence() {
    }
 
    /** First and last positions of target in an ascending array, or {-1, -1}. O(log n). */
    public static int[] find(int[] scores, int target) {
        int first = lowerBound(scores, target);
        if (first == scores.length || scores[first] != target) {
            return new int[] {-1, -1};
        }
        int last = lowerBound(scores, target + 1) - 1;
        return new int[] {first, last};
    }
 
    /** The first index whose value is at least x (scores.length if none). */
    private static int lowerBound(int[] scores, int x) {
        int lo = 0, hi = scores.length;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (scores[mid] < x) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        return lo;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/FirstLastOccurrence.java

#pragma once
 
#include <cstddef>
#include <span>
#include <utility>
 
namespace bekadan::dsa::problems {
 
// The first index whose value is at least x (scores.size() if none); std::lower_bound does the same.
inline std::ptrdiff_t lower_bound_index(std::span<const int> scores, int x) {
    std::ptrdiff_t lo = 0, hi = std::ssize(scores);
    while (lo < hi) {
        const std::ptrdiff_t mid = lo + (hi - lo) / 2;
        if (scores[static_cast<std::size_t>(mid)] < x)
            lo = mid + 1;
        else
            hi = mid;
    }
    return lo;
}
 
// First and last positions of target in an ascending span, or {-1, -1}. O(log n).
inline std::pair<std::ptrdiff_t, std::ptrdiff_t> first_last_occurrence(std::span<const int> scores, int target) {
    const std::ptrdiff_t first = lower_bound_index(scores, target);
    if (first == std::ssize(scores) || scores[static_cast<std::size_t>(first)] != target)
        return {-1, -1};
    const std::ptrdiff_t last = lower_bound_index(scores, target + 1) - 1;
    return {first, last};
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/first_last_occurrence.hpp