First and last position
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
- lo
- 0
- mid
- 3
- hi
- 7
- nums[mid]
- 4
- target
- 4
Example 1 · Expressing upperBound in terms of lowerBound
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)); }}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 indexiin0 .. nsuch thatnums[i] >= target(ornif all elements are< target).upperBound(nums, target): the smallest indexiin0 .. nsuch thatnums[i] > target(ornif all elements are<= target).- The only difference between
lowerBoundandupperBoundin code is one character:nums[mid] >= targetvsnums[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):
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.
- To find the first occurrence: when
nums[mid] == target, saveans = midand move left (hi = mid - 1). - To find the last occurrence: when
nums[mid] == target, saveans = midand move right (lo = mid + 1).
Example 2 · First and last position of target using ans = -1 template
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))); }}[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)
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); }}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
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))); }}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 = 4copies (indices1, 2, 3, 4). - For
x = 5(absent):upperBound(5) - lowerBound(5) = 5 - 5 = 0copies. - More generally, the number of elements in the inclusive value range
[L, R]is simplyupperBound(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.
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 oftarget).
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 firstThis is exact solution to Search Insert Position.
upperBound(nums, target)gives the latest valid insertion index (inserting after any existing copies oftarget).
Next step
Check your understanding
10 quick questions