Skip to lesson

First and last position

When a sorted array contains duplicate values—such as nums = [2, 4, 4, 4, 4, 7, 9]—classic binary search stops at whichever 4 it lands on first (here index 3). If you try to walk left and right from index 3 to find all the 4s, an array of a million 4s degrades your runtime from O(log n) all the way back to O(n)! To stay O(log n) even with duplicates, we use lower bound and upper bound.

Lower bound and upper bound

Two boundary functions (borrowed from C++ STL's std::lower_bound and std::upper_bound and used throughout competitive programming and interviews) answer almost every range question on a sorted array.

Finding lowerBound(nums, 4) in [2, 4, 4, 4, 4, 7, 9]

Step 1 of 4

Array: 2, 4, 4, 4, 4, 7, 9. lo at index 0. mid at index 3.
lo
0
mid
3
hi
7
nums[mid]
4
target
4
Start with half-open [lo=0, hi=7). At mid = 3, nums[3] = 4 >= 4. Instead of stopping, pull hi = mid = 3 to keep searching left for an earlier 4.

Example 1 · Expressing upperBound in terms of lowerBound

OneFunctionTrickDemo.javaJava
public class OneFunctionTrickDemo {    public static int lowerBound(int[] nums, int target) {        int lo = 0, hi = nums.length;        while (lo < hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] >= target) hi = mid;            else lo = mid + 1;        }        return lo;    }
    public static void main(String[] args) {        int[] nums = {1, 3, 3, 3, 5, 8};        // For integers, nums[i] > x is equivalent to nums[i] >= x + 1!        int firstIdx = lowerBound(nums, 3);        int afterLastIdx = lowerBound(nums, 3 + 1);        System.out.println("First 3 at: " + firstIdx + ", last 3 at: " + (afterLastIdx - 1));    }}
Output
First 3 at: 1, last 3 at: 3

What this code does

  • For integer arrays (when target < Integer.MAX_VALUE), 'strictly greater than x' is identical to 'greater than or equal to x + 1'.
  • So you only need to write lowerBound(nums, x) once: upperBound(nums, x) is simply lowerBound(nums, x + 1)!

In detail:

  • lowerBound(nums, target): the smallest index i in 0 .. n such that nums[i] >= target (or n if all elements are < target).
  • upperBound(nums, target): the smallest index i in 0 .. n such that nums[i] > target (or n if all elements are <= target).
  • The only difference between lowerBound and upperBound in code is one character: nums[mid] >= target vs nums[mid] > target!

Suppose nums = [2, 4, 4, 4, 4, 7, 9] (indices 0 .. 6) and target = 4. Then lowerBound(nums, 4) returns index 1 (the first element >= 4), and upperBound(nums, 4) returns index 5 (the first element > 4, which is 7). Notice how both functions search the index range [0 .. n] (because if every element in nums is smaller than target, the first position is n):

With lo = 0, hi = nums.length (half-open [lo, hi)), when nums[mid] satisfies the condition (>= target or > target), mid might be the answer, so we set hi = mid; otherwise mid is too small, so we set lo = mid + 1.

First and last occurrence

You can also write firstOccurrence and lastOccurrence directly using your familiar while (lo <= hi) loop and an ans = -1 variable.

  1. To find the first occurrence: when nums[mid] == target, save ans = mid and move left (hi = mid - 1).
  2. To find the last occurrence: when nums[mid] == target, save ans = mid and move right (lo = mid + 1).

Example 2 · First and last position of target using ans = -1 template

FirstAndLastPositionDemo.javaJava
import java.util.Arrays;
public class FirstAndLastPositionDemo {    public static int findBound(int[] nums, int target, boolean findFirst) {        int lo = 0, hi = nums.length - 1, ans = -1;        while (lo <= hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] == target) {                ans = mid;                if (findFirst) {                    hi = mid - 1; // keep looking left                } else {                    lo = mid + 1; // keep looking right                }            } else if (nums[mid] < target) {                lo = mid + 1;            } else {                hi = mid - 1;            }        }        return ans;    }
    public static int[] searchRange(int[] nums, int target) {        int first = findBound(nums, target, true);        if (first == -1) return new int[]{-1, -1};        int last = findBound(nums, target, false);        return new int[]{first, last};    }
    public static void main(String[] args) {        int[] nums = {5, 7, 7, 8, 8, 8, 10};        System.out.println(Arrays.toString(searchRange(nums, 8)));        System.out.println(Arrays.toString(searchRange(nums, 6)));    }}
Output
[3, 5]
[-1, -1]

What this code does

  • When nums[mid] == 8, findFirst sets ans = mid and hi = mid - 1 to check if an earlier 8 exists to the left.
  • If findFirst returns -1, 6 is not in the array at all, so we skip the second binary search.

When nums[mid] == target, instead of returning mid immediately, you record ans = mid and keep searching the half where an even earlier (or even later) copy could hide: Equivalently, using lowerBound and upperBound: if lb = lowerBound(nums, target) has lb < n && nums[lb] == target, then the first occurrence is lb and the last occurrence is upperBound(nums, target) - 1!

Counting a value

Once you know the half-open range [lowerBound(nums, x), upperBound(nums, x)) that contains all copies of x, counting how many times x appears in nums takes a single subtraction—with zero special cases when x is absent!

Example 3 · Brute force: scan the whole array for every question (O(n) time, O(1) space)

CountByScanning.javaJava
public class CountByScanning {    public static void main(String[] args) {        int[] nums = {2, 4, 4, 4, 4, 7, 9};        int looked = 0;        int count4 = 0, count5 = 0;        for (int x : nums) {            looked++;            if (x == 4) count4++;            if (x == 5) count5++;        }        System.out.println("count(4)=" + count4);        System.out.println("count(5)=" + count5);        System.out.println("Elements looked at: " + looked);    }}
Output
count(4)=4
count(5)=0
Elements looked at: 7

What this code does

  • Counting the 4s and the 5s looks at all 7 elements; every new question scans the array again.
  • It is slow because equal values sit side by side in a sorted array, and a scan never uses that.

Example 4 · Optimal: lowerBound and upperBound count in O(log n) time, O(1) space

LowerUpperBoundDemo.javaJava
public class LowerUpperBoundDemo {    // First index i in [0..n] with nums[i] >= target    public static int lowerBound(int[] nums, int target) {        int lo = 0, hi = nums.length;        while (lo < hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] >= target) {                hi = mid;            } else {                lo = mid + 1;            }        }        return lo;    }
    // First index i in [0..n] with nums[i] > target    public static int upperBound(int[] nums, int target) {        int lo = 0, hi = nums.length;        while (lo < hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] > target) {                hi = mid;            } else {                lo = mid + 1;            }        }        return lo;    }
    public static void main(String[] args) {        int[] nums = {2, 4, 4, 4, 4, 7, 9};        System.out.println("lb(4)=" + lowerBound(nums, 4) + ", ub(4)=" + upperBound(nums, 4));        System.out.println("count(4)=" + (upperBound(nums, 4) - lowerBound(nums, 4)));        System.out.println("count(5)=" + (upperBound(nums, 5) - lowerBound(nums, 5)));        System.out.println("count in [3..7]=" + (upperBound(nums, 7) - lowerBound(nums, 3)));    }}
Output
lb(4)=1, ub(4)=5
count(4)=4
count(5)=0
count in [3..7]=5

What this code does

  • All copies of 4 sit in the half-open slice [lb(4), ub(4)) = [1, 5), whose length is 5 - 1 = 4.
  • All elements with values in [3..7] sit in [lb(3), ub(7)) = [1, 6), giving 6 - 1 = 5 elements (four 4s and one 7).
  • Two binary searches (about log₂ 7 steps each) replace the full scan, because all copies of a value form one block that the two bounds mark.
  • Count of x = upperBound(nums, x) - lowerBound(nums, x).
  • Count of elements with L <= nums[i] <= R = upperBound(nums, R) - lowerBound(nums, L).

In nums = [2, 4, 4, 4, 4, 7, 9]:

  • For x = 4: upperBound(4) - lowerBound(4) = 5 - 1 = 4 copies (indices 1, 2, 3, 4).
  • For x = 5 (absent): upperBound(5) - lowerBound(5) = 5 - 5 = 0 copies.
  • More generally, the number of elements in the inclusive value range [L, R] is simply upperBound(nums, R) - lowerBound(nums, L) in O(log n) time!

Predict the output

Which index does the search return?

The array is {2, 4, 4, 4, 4, 7, 9}. Pick what each program prints.

Round 1 of 2

First index whose value is at least 4.

public class FirstAtLeast {
public static void main(String[] args) {
int[] a = {2, 4, 4, 4, 4, 7, 9};
int lo = 0, hi = a.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] >= 4) hi = mid;
else lo = mid + 1;
}
System.out.println(lo);
}
}

Insert position

The insert position of target is an index where you can insert it so that nums stays sorted. There are two:

  • lowerBound(nums, target) gives the earliest valid insertion index (inserting before any existing copies of target).
Java
int[] nums = {1, 2, 2, 3};int earliest = lowerBound(nums, 2); // 1: insert before the existing 2sint latest = upperBound(nums, 2);   // 3: insert after the existing 2sint first = lowerBound(nums, 0);    // 0: smaller than everything, goes first

This is exact solution to Search Insert Position.

  • upperBound(nums, target) gives the latest valid insertion index (inserting after any existing copies of target).

Next step

Check your understanding

10 quick questions