10.3 Finding boundaries with binary search¶
10.3.1 Finding the left boundary¶
Question
Given a sorted array nums of length \(n\) that may contain duplicates, return the index of the leftmost occurrence of target. If the value is absent, return \(-1\).
Recall how binary search finds an insertion point. When the search ends, \(i\) points to the leftmost occurrence of target. Thus, finding the insertion point is essentially finding the index of the leftmost occurrence of target.
We can use the insertion-point function to find the left boundary. If the array does not contain target, one of two things will happen.
- The insertion index \(i\) is out of bounds.
- The element
nums[i]differs fromtarget.
In either case, return \(-1\), as shown below:
def binary_search_left_edge(nums: list[int], target: int) -> int:
"""Use binary search to find the leftmost occurrence of target"""
# Equivalent to finding the insertion point for target
i = binary_search_insertion(nums, target)
# Target not found. Return -1
if i == len(nums) or nums[i] != target:
return -1
# Found target. Return index i
return i
/* Use binary search to find the leftmost occurrence of target */
int binarySearchLeftEdge(vector<int> &nums, int target) {
// Equivalent to finding the insertion point for target
int i = binarySearchInsertion(nums, target);
// Target not found. Return -1
if (i == nums.size() || nums[i] != target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
int binarySearchLeftEdge(int[] nums, int target) {
// Equivalent to finding the insertion point for target
int i = binary_search_insertion.binarySearchInsertion(nums, target);
// Target not found. Return -1
if (i == nums.length || nums[i] != target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
int BinarySearchLeftEdge(int[] nums, int target) {
// Equivalent to finding the insertion point for target
int i = binary_search_insertion.BinarySearchInsertion(nums, target);
// Target not found. Return -1
if (i == nums.Length || nums[i] != target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
func binarySearchLeftEdge(nums []int, target int) int {
// Equivalent to finding the insertion point for target
i := binarySearchInsertion(nums, target)
// Target not found. Return -1
if i == len(nums) || nums[i] != target {
return -1
}
// Found target. Return index i
return i
}
/* Use binary search to find the leftmost occurrence of target */
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
// Equivalent to finding the insertion point for target
let i = binarySearchInsertion(nums: nums, target: target)
// Target not found. Return -1
if i == nums.endIndex || nums[i] != target {
return -1
}
// Found target. Return index i
return i
}
/* Use binary search to find the leftmost occurrence of target */
function binarySearchLeftEdge(nums, target) {
// Equivalent to finding the insertion point for target
const i = binarySearchInsertion(nums, target);
// Target not found. Return -1
if (i === nums.length || nums[i] !== target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
function binarySearchLeftEdge(nums: Array<number>, target: number): number {
// Equivalent to finding the insertion point for target
const i = binarySearchInsertion(nums, target);
// Target not found. Return -1
if (i === nums.length || nums[i] !== target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
int binarySearchLeftEdge(List<int> nums, int target) {
// Equivalent to finding the insertion point for target
int i = binarySearchInsertion(nums, target);
// Target not found. Return -1
if (i == nums.length || nums[i] != target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
fn binary_search_left_edge(nums: &[i32], target: i32) -> i32 {
// Equivalent to finding the insertion point for target
let i = binary_search_insertion(nums, target);
// Target not found. Return -1
if i == nums.len() as i32 || nums[i as usize] != target {
return -1;
}
// Found target. Return index i
i
}
/* Use binary search to find the leftmost occurrence of target */
int binarySearchLeftEdge(int *nums, int numSize, int target) {
// Equivalent to finding the insertion point for target
int i = binarySearchInsertion(nums, numSize, target);
// Target not found. Return -1
if (i == numSize || nums[i] != target) {
return -1;
}
// Found target. Return index i
return i;
}
/* Use binary search to find the leftmost occurrence of target */
fun binarySearchLeftEdge(nums: IntArray, target: Int): Int {
// Equivalent to finding the insertion point for target
val i = binarySearchInsertion(nums, target)
// Target not found. Return -1
if (i == nums.size || nums[i] != target) {
return -1
}
// Found target. Return index i
return i
}
### Use binary search to find the leftmost occurrence of target ###
def binary_search_left_edge(nums, target)
# Equivalent to finding the insertion point for target
i = binary_search_insertion(nums, target)
# Target not found. Return -1
return -1 if i == nums.length || nums[i] != target
i # Found target. Return index i
end
Visualize execution
10.3.2 Finding the right boundary¶
How can we find the rightmost occurrence of target? The most direct approach is to change how the pointers narrow the interval when nums[m] == target. Try implementing this version yourself.
Here are two shortcuts.
1. Reusing the left-boundary search¶
We can use the function that finds the leftmost occurrence to find the rightmost one: to locate the rightmost target, search for the leftmost target + 1.
As Figure 10-7 shows, when the search ends, \(i\) points to the leftmost target + 1 (if present), and \(j\) points to the rightmost target. Return \(j\) to get the right boundary.
Figure 10-7 Turning a right-boundary search into a left-boundary search
Description of Figure 10-7: Finding the right boundary using an insertion point
In a sorted integer array, subtract 1 from the insertion index for target + 1 to get a candidate right boundary. Before returning it, check that the index is valid and the element there equals target.
The sorted integer array is nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15], and target = 6. Five consecutive 6s occupy indices 2 through 6. The diagram shows the final positions of both pointers for each of the two boundary searches.
The left panel searches directly for the leftmost target. When the binary search for the insertion point ends, i is at index 2 (the first 6, highlighted in teal), and j is at index 1 (value 3). The left boundary for 6 is therefore i = 2.
The right panel uses a double-headed arrow labeled “Equivalent” to connect finding the rightmost target with finding the leftmost target + 1. A binary search for the insertion point of target + 1 = 7 ends with i at the first element greater than or equal to 7 (the value 10 at index 7). The pointer j = i − 1 lands at index 6, the last 6, highlighted in teal. The array contains no 7. Here, finding the leftmost target + 1 means calling the binary insertion-point function to find the leftmost position for a 7, i = 7.
This equivalence relies on the elements being integers. Every element greater than 6 is at least 7, so the first position with a value of at least 7 is also the first with a value greater than 6. After computing j = i − 1, check that j is in bounds and nums[j] == target. If either check fails, target is absent and the code should return −1.
The insertion-point function returns \(i\). Subtract \(1\) from it to obtain \(j\):
def binary_search_right_edge(nums: list[int], target: int) -> int:
"""Use binary search to find the rightmost occurrence of target"""
# Search for the leftmost occurrence of target + 1
i = binary_search_insertion(nums, target + 1)
# j points to the rightmost occurrence of target, and i to the first larger element
j = i - 1
# Target not found. Return -1
if j == -1 or nums[j] != target:
return -1
# Found target. Return index j
return j
/* Use binary search to find the rightmost occurrence of target */
int binarySearchRightEdge(vector<int> &nums, int target) {
// Search for the leftmost occurrence of target + 1
int i = binarySearchInsertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
int j = i - 1;
// Target not found. Return -1
if (j == -1 || nums[j] != target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
int binarySearchRightEdge(int[] nums, int target) {
// Search for the leftmost occurrence of target + 1
int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
int j = i - 1;
// Target not found. Return -1
if (j == -1 || nums[j] != target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
int BinarySearchRightEdge(int[] nums, int target) {
// Search for the leftmost occurrence of target + 1
int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
int j = i - 1;
// Target not found. Return -1
if (j == -1 || nums[j] != target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
func binarySearchRightEdge(nums []int, target int) int {
// Search for the leftmost occurrence of target + 1
i := binarySearchInsertion(nums, target+1)
// j points to the rightmost occurrence of target, and i to the first larger element
j := i - 1
// Target not found. Return -1
if j == -1 || nums[j] != target {
return -1
}
// Found target. Return index j
return j
}
/* Use binary search to find the rightmost occurrence of target */
func binarySearchRightEdge(nums: [Int], target: Int) -> Int {
// Search for the leftmost occurrence of target + 1
let i = binarySearchInsertion(nums: nums, target: target + 1)
// j points to the rightmost occurrence of target, and i to the first larger element
let j = i - 1
// Target not found. Return -1
if j == -1 || nums[j] != target {
return -1
}
// Found target. Return index j
return j
}
/* Use binary search to find the rightmost occurrence of target */
function binarySearchRightEdge(nums, target) {
// Search for the leftmost occurrence of target + 1
const i = binarySearchInsertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
const j = i - 1;
// Target not found. Return -1
if (j === -1 || nums[j] !== target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
function binarySearchRightEdge(nums: Array<number>, target: number): number {
// Search for the leftmost occurrence of target + 1
const i = binarySearchInsertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
const j = i - 1;
// Target not found. Return -1
if (j === -1 || nums[j] !== target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
int binarySearchRightEdge(List<int> nums, int target) {
// Search for the leftmost occurrence of target + 1
int i = binarySearchInsertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
int j = i - 1;
// Target not found. Return -1
if (j == -1 || nums[j] != target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
fn binary_search_right_edge(nums: &[i32], target: i32) -> i32 {
// Search for the leftmost occurrence of target + 1
let i = binary_search_insertion(nums, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
let j = i - 1;
// Target not found. Return -1
if j == -1 || nums[j as usize] != target {
return -1;
}
// Found target. Return index j
j
}
/* Use binary search to find the rightmost occurrence of target */
int binarySearchRightEdge(int *nums, int numSize, int target) {
// Search for the leftmost occurrence of target + 1
int i = binarySearchInsertion(nums, numSize, target + 1);
// j points to the rightmost occurrence of target, and i to the first larger element
int j = i - 1;
// Target not found. Return -1
if (j == -1 || nums[j] != target) {
return -1;
}
// Found target. Return index j
return j;
}
/* Use binary search to find the rightmost occurrence of target */
fun binarySearchRightEdge(nums: IntArray, target: Int): Int {
// Search for the leftmost occurrence of target + 1
val i = binarySearchInsertion(nums, target + 1)
// j points to the rightmost occurrence of target, and i to the first larger element
val j = i - 1
// Target not found. Return -1
if (j == -1 || nums[j] != target) {
return -1
}
// Found target. Return index j
return j
}
### Use binary search to find the rightmost occurrence of target ###
def binary_search_right_edge(nums, target)
# Search for the leftmost occurrence of target + 1
i = binary_search_insertion(nums, target + 1)
# j points to the rightmost occurrence of target, and i to the first larger element
j = i - 1
# Target not found. Return -1
return -1 if j == -1 || nums[j] != target
j # Found target. Return index j
end
Visualize execution
2. Finding a boundary by searching for a value¶
When the array does not contain target, the final positions of \(i\) and \(j\) mark the first element greater than target and the rightmost element less than target, respectively.
We can therefore find either boundary by searching for a value we know is absent, as Figure 10-8 shows.
- To find the leftmost
target, search fortarget - 0.5and return the pointer \(i\). - To find the rightmost
target, search fortarget + 0.5and return the pointer \(j\).
Figure 10-8 Finding a boundary by searching for a value
Description of Figure 10-8: Finding left and right boundaries using half-integers
In an integer array, search for two half-integers that cannot occur in the array to locate the boundaries of a repeated value.
The sorted integer array is nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]. The target value 6 (target = 6) occupies indices 2 through 6. Since all elements are integers, neither target - 0.5 = 5.5 nor target + 0.5 = 6.5 can occur in the array.
When a closed-interval binary search looks for an absent value, it never takes the equality branch. Once the interval is empty, i points to the first element greater than the search value, and j to the rightmost element less than it. If there is no greater element, i = n. If there is no smaller element, j = −1. In each case the corresponding pointer is outside the array.
The left panel shows how finding the leftmost target is equivalent to searching for target - 0.5 (5.5). The search ends with j = 1 at the value 3 and i = 2 at the first element greater than 5.5, the leftmost 6. Returning i = 2 gives the left boundary. The right panel shows how finding the rightmost target is equivalent to searching for target + 0.5 (6.5). The search ends with j = 6 at the rightmost element less than 6.5, the last 6, and i = 7 at the value 10. Returning j = 6 gives the right boundary.
This method depends on all elements being integers. If the array contains fractional values, adding or subtracting 0.5 could produce an existing element and invalidate the method. In a general implementation where target may be absent, verify that the index is in bounds and the element equals target before returning it.
The code is omitted here. Keep two details in mind.
- The given array contains only integers, so the equality case cannot arise for these fractional search values.
- Since this method introduces fractional values, change the function's
targetvariable to a floating-point type. Python requires no change.