Tech Interview RoomStudy guides

Binary Search

Find the first and last position of a target in a sorted array. Compare linear scan, Arrays.binarySearch and lower/upper bound.

Beginner · 2 min read · Lesson 1 of 3 in Binary Search

Problem

nums = [5, 7, 7, 8, 8, 10], target = 8 → [3, 4]; target 6 → [-1, -1].

Pattern

Lower bound / upper bound binary search: instead of stopping when you find the target, keep searching left (first occurrence) or right (last occurrence). Template: lo = 0, hi = n; while lo < hi, mid = lo + (hi - lo) / 2; move one side.

Approach 1: Linear scan (feasible, O(n))

java
class RangeLinear {
    static int[] find(int[] a, int target) {
        int first = -1, last = -1;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == target) { if (first == -1) first = i; last = i; }
        }
        return new int[] {first, last};
    }
}

Approach 2: Arrays.binarySearch, then expand (O(log n + k))

Arrays.binarySearch returns some matching index, not necessarily the first; expanding is O(k) for k duplicates, O(n) in the worst case.

java
import java.util.Arrays;

class RangeJdkSearch {
    static int[] find(int[] a, int target) {
        int i = Arrays.binarySearch(a, target);
        if (i < 0) return new int[] {-1, -1};
        int first = i, last = i;
        while (first > 0 && a[first - 1] == target) first--;
        while (last < a.length - 1 && a[last + 1] == target) last++;
        return new int[] {first, last};
    }
}

Approach 3: Two bounded binary searches (O(log n)) — optimal

java
class RangeBounds {
    // first index with a[i] >= target
    static int lowerBound(int[] a, int target) {
        int lo = 0, hi = a.length;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;                        // avoids int overflow of (lo + hi) / 2
            if (a[mid] < target) lo = mid + 1; else hi = mid;
        }
        return lo;
    }
    // first index with a[i] > target
    static int upperBound(int[] a, int target) {
        int lo = 0, hi = a.length;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] <= target) lo = mid + 1; else hi = mid;
        }
        return lo;
    }
    static int[] find(int[] a, int target) {
        int first = lowerBound(a, target);
        if (first == a.length || a[first] != target) return new int[] {-1, -1};
        return new int[] {first, upperBound(a, target) - 1};
    }
}

class RangeDemo {
    public static void main(String[] args) {
        int[] a = {5, 7, 7, 8, 8, 10};
        for (int t : new int[] {8, 6, 5, 10}) {
            System.out.println(t + ": " + java.util.Arrays.toString(RangeLinear.find(a, t)) + " "
                + java.util.Arrays.toString(RangeJdkSearch.find(a, t)) + " " + java.util.Arrays.toString(RangeBounds.find(a, t)));
        }
        System.out.println("count of 7 = " + (RangeBounds.upperBound(a, 7) - RangeBounds.lowerBound(a, 7)));   // 2
    }
}

Feasible → optimal

Linear O(n) → binary search plus expansion O(log n + k) → two bound searches O(log n) regardless of duplicates. Bonus: upperBound − lowerBound counts occurrences in O(log n).

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): search insert position, floor and ceiling.

lowerBound(target) is the insert position. Ceiling = a[lowerBound] (if in range); floor = a[upperBound - 1]. In Java collections, TreeSet.floor/ceiling and TreeMap.floorKey/ceilingKey do this in O(log n).

Related (same pattern): square root of x (integer part) without Math.sqrt.

Binary search the largest m with m * m <= x over [0, x], using long for m * m. O(log x). It is the same "last value satisfying a condition" template.