Skip to content

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 duplicate elements, return the index of the leftmost occurrence of target. If the array does not contain this element, return \(-1\).

Recall the method for finding an insertion point with binary search: when the search finishes, \(i\) points to the leftmost target. Finding the insertion point therefore amounts to finding the index of the leftmost target.

We can use the insertion-point function to find the left boundary. However, target may be absent from the array, leading to either of the following outcomes.

  • The insertion index \(i\) is out of bounds.
  • nums[i] is not equal to target.

In either case, simply return \(-1\). The code is as follows:

binary_search_edge.py
def binary_search_left_edge(nums: list[int], target: int) -> int:
    """Find the leftmost occurrence of target using binary search"""
    # This is equivalent to finding the insertion point of target
    i = binary_search_insertion(nums, target)
    # If target was not found, return -1
    if i == len(nums) or nums[i] != target:
        return -1
    # Target was found; return index i
    return i
binary_search_edge.cpp
/* Find the leftmost occurrence of target using binary search */
int binarySearchLeftEdge(vector<int> &nums, int target) {
    // This is equivalent to finding the insertion point of target
    int i = binarySearchInsertion(nums, target);
    // If target was not found, return -1
    if (i == nums.size() || nums[i] != target) {
        return -1;
    }
    // Target was found; return index i
    return i;
}
binary_search_edge.java
/* Find the leftmost occurrence of target using binary search */
int binarySearchLeftEdge(int[] nums, int target) {
    // This is equivalent to finding the insertion point of target
    int i = binary_search_insertion.binarySearchInsertion(nums, target);
    // If target was not found, return -1
    if (i == nums.length || nums[i] != target) {
        return -1;
    }
    // Target was found; return index i
    return i;
}
binary_search_edge.cs
/* Find the leftmost occurrence of target using binary search */
int BinarySearchLeftEdge(int[] nums, int target) {
    // This is equivalent to finding the insertion point of target
    int i = binary_search_insertion.BinarySearchInsertion(nums, target);
    // If target was not found, return -1
    if (i == nums.Length || nums[i] != target) {
        return -1;
    }
    // Target was found; return index i
    return i;
}
binary_search_edge.go
/* Find the leftmost occurrence of target using binary search */
func binarySearchLeftEdge(nums []int, target int) int {
    // This is equivalent to finding the insertion point of target
    i := binarySearchInsertion(nums, target)
    // If target was not found, return -1
    if i == len(nums) || nums[i] != target {
        return -1
    }
    // Target was found; return index i
    return i
}
binary_search_edge.swift
/* Find the leftmost occurrence of target using binary search */
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
    // This is equivalent to finding the insertion point of target
    let i = binarySearchInsertion(nums: nums, target: target)
    // If target was not found, return -1
    if i == nums.endIndex || nums[i] != target {
        return -1
    }
    // Target was found; return index i
    return i
}
binary_search_edge.js
/* Find the leftmost occurrence of target using binary search */
function binarySearchLeftEdge(nums, target) {
    // This is equivalent to finding the insertion point of target
    const i = binarySearchInsertion(nums, target);
    // If target was not found, return -1
    if (i === nums.length || nums[i] !== target) {
        return -1;
    }
    // Target was found; return index i
    return i;
}
binary_search_edge.ts
/* Find the leftmost occurrence of target using binary search */
function binarySearchLeftEdge(nums: Array<number>, target: number): number {
    // This is equivalent to finding the insertion point of target
    const i = binarySearchInsertion(nums, target);
    // If target was not found, return -1
    if (i === nums.length || nums[i] !== target) {
        return -1;
    }
    // Target was found; return index i
    return i;
}
binary_search_edge.dart
/* Find the leftmost occurrence of target using binary search */
int binarySearchLeftEdge(List<int> nums, int target) {
  // This is equivalent to finding the insertion point of target
  int i = binarySearchInsertion(nums, target);
  // If target was not found, return -1
  if (i == nums.length || nums[i] != target) {
    return -1;
  }
  // Target was found; return index i
  return i;
}
binary_search_edge.rs
/* Find the leftmost occurrence of target using binary search */
fn binary_search_left_edge(nums: &[i32], target: i32) -> i32 {
    // This is equivalent to finding the insertion point of target
    let i = binary_search_insertion(nums, target);
    // If target was not found, return -1
    if i == nums.len() as i32 || nums[i as usize] != target {
        return -1;
    }
    // Target was found; return index i
    i
}
binary_search_edge.c
/* Find the leftmost occurrence of target using binary search */
int binarySearchLeftEdge(int *nums, int numSize, int target) {
    // This is equivalent to finding the insertion point of target
    int i = binarySearchInsertion(nums, numSize, target);
    // If target was not found, return -1
    if (i == numSize || nums[i] != target) {
        return -1;
    }
    // Target was found; return index i
    return i;
}
binary_search_edge.kt
/* Find the leftmost occurrence of target using binary search */
fun binarySearchLeftEdge(nums: IntArray, target: Int): Int {
    // This is equivalent to finding the insertion point of target
    val i = binarySearchInsertion(nums, target)
    // If target was not found, return -1
    if (i == nums.size || nums[i] != target) {
        return -1
    }
    // Target was found; return index i
    return i
}
binary_search_edge.rb
### Find the leftmost occurrence of target using binary search ###
def binary_search_left_edge(nums, target)
  # This is equivalent to finding the insertion point of target
  i = binary_search_insertion(nums, target)

  # If target was not found, return -1
  return -1 if i == nums.length || nums[i] != target

  i # Target was found; return index i
end
Visualize execution

10.3.2   Finding the right boundary

How can we find the rightmost target? The most direct approach is to modify the pointer update for nums[m] == target. We omit the code here; interested readers can implement it themselves.

Here are two shortcuts.

We can use the function for finding the leftmost element to find the rightmost one: turn the search for the rightmost target into a search for the leftmost target + 1.

As shown below, when the search finishes, pointer \(i\) points to the leftmost target + 1, if it exists, while \(j\) points to the rightmost target. We therefore return \(j\).

Turning a right-boundary search into a left-boundary search

Figure 10-7   Turning a right-boundary search into a left-boundary search

The returned insertion point is \(i\), so subtract \(1\) to obtain \(j\):

binary_search_edge.py
def binary_search_right_edge(nums: list[int], target: int) -> int:
    """Find the rightmost occurrence of target using binary search"""
    # Reduce the problem to finding the leftmost insertion point of target + 1
    i = binary_search_insertion(nums, target + 1)
    # j is the candidate rightmost target index; i is the index of the first element greater than target, or len(nums)
    j = i - 1
    # If target was not found, return -1
    if j == -1 or nums[j] != target:
        return -1
    # Target was found; return index j
    return j
binary_search_edge.cpp
/* Find the rightmost occurrence of target using binary search */
int binarySearchRightEdge(vector<int> &nums, int target) {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    int i = binarySearchInsertion(nums, target + 1);
    // j points to the rightmost target, while i points to the first element greater than target
    int j = i - 1;
    // If target was not found, return -1
    if (j == -1 || nums[j] != target) {
        return -1;
    }
    // Target was found; return index j
    return j;
}
binary_search_edge.java
/* Find the rightmost occurrence of target using binary search */
int binarySearchRightEdge(int[] nums, int target) {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
    // j points to the rightmost target, while i points to the first element greater than target
    int j = i - 1;
    // If target was not found, return -1
    if (j == -1 || nums[j] != target) {
        return -1;
    }
    // Target was found; return index j
    return j;
}
binary_search_edge.cs
/* Find the rightmost occurrence of target using binary search */
int BinarySearchRightEdge(int[] nums, int target) {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1);
    // j is the candidate index of the rightmost target; i is the insertion point after all elements <= target
    int j = i - 1;
    // If target was not found, return -1
    if (j == -1 || nums[j] != target) {
        return -1;
    }
    // Target was found; return index j
    return j;
}
binary_search_edge.go
/* Find the rightmost occurrence of target using binary search */
func binarySearchRightEdge(nums []int, target int) int {
    // For integer values, find the leftmost insertion point of target + 1 (assuming no overflow)
    i := binarySearchInsertion(nums, target+1)
    // i is the index of the first element greater than target (or len(nums)); j is the candidate index of the rightmost target
    j := i - 1
    // If target was not found, return -1
    if j == -1 || nums[j] != target {
        return -1
    }
    // Target was found; return index j
    return j
}
binary_search_edge.swift
/* Find the rightmost occurrence of target using binary search */
func binarySearchRightEdge(nums: [Int], target: Int) -> Int {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    let i = binarySearchInsertion(nums: nums, target: target + 1)
    // i is the first index with a value greater than target (or nums.endIndex); j is the candidate index of the rightmost target
    let j = i - 1
    // If target was not found, return -1
    if j == -1 || nums[j] != target {
        return -1
    }
    // Target was found; return index j
    return j
}
binary_search_edge.js
/* Find the rightmost occurrence of target using binary search */
function binarySearchRightEdge(nums, target) {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    const i = binarySearchInsertion(nums, target + 1);
    // j points to the rightmost target, while i points to the first element greater than target
    const j = i - 1;
    // If target was not found, return -1
    if (j === -1 || nums[j] !== target) {
        return -1;
    }
    // Target was found; return index j
    return j;
}
binary_search_edge.ts
/* Find the rightmost occurrence of target using binary search */
function binarySearchRightEdge(nums: Array<number>, target: number): number {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    const i = binarySearchInsertion(nums, target + 1);
    // For integer elements, i is the first index greater than target (or the array length); j is the candidate rightmost target index
    const j = i - 1;
    // If target was not found, return -1
    if (j === -1 || nums[j] !== target) {
        return -1;
    }
    // Target was found; return index j
    return j;
}
binary_search_edge.dart
/* Find the rightmost occurrence of target using binary search */
int binarySearchRightEdge(List<int> nums, int target) {
  // Reduce the problem to finding the leftmost insertion point of target + 1
  int i = binarySearchInsertion(nums, target + 1);
  // i is the first index greater than target (or the array length); j is the candidate rightmost target index
  int j = i - 1;
  // If target was not found, return -1
  if (j == -1 || nums[j] != target) {
    return -1;
  }
  // Target was found; return index j
  return j;
}
binary_search_edge.rs
/* Find the rightmost occurrence of target using binary search */
fn binary_search_right_edge(nums: &[i32], target: i32) -> i32 {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    let i = binary_search_insertion(nums, target + 1);
    // j points to the rightmost target, while i points to the first element greater than target
    let j = i - 1;
    // If target was not found, return -1
    if j == -1 || nums[j as usize] != target {
        return -1;
    }
    // Target was found; return index j
    j
}
binary_search_edge.c
/* Find the rightmost occurrence of target using binary search */
int binarySearchRightEdge(int *nums, int numSize, int target) {
    // Reduce the problem to finding the leftmost insertion point of target + 1
    int i = binarySearchInsertion(nums, numSize, target + 1);
    // j points to the rightmost target, while i points to the first element greater than target
    int j = i - 1;
    // If target was not found, return -1
    if (j == -1 || nums[j] != target) {
        return -1;
    }
    // Target was found; return index j
    return j;
}
binary_search_edge.kt
/* Find the rightmost occurrence of target using binary search */
fun binarySearchRightEdge(nums: IntArray, target: Int): Int {
    // For integer values, find the leftmost insertion point of target + 1 (assuming no overflow)
    val i = binarySearchInsertion(nums, target + 1)
    // i is the index of the first element greater than target (or the array length); j is the candidate rightmost target index
    val j = i - 1
    // If target was not found, return -1
    if (j == -1 || nums[j] != target) {
        return -1
    }
    // Target was found; return index j
    return j
}
binary_search_edge.rb
### Find the rightmost occurrence of target using binary search ###
def binary_search_right_edge(nums, target)
  # For integer elements, find the leftmost insertion point of target + 1
  i = binary_search_insertion(nums, target + 1)

  # i is the index of the first element greater than target (or the array length); j is the candidate rightmost target index
  j = i - 1

  # If target was not found, return -1
  return -1 if j == -1 || nums[j] != target

  j # Target was found; return index j
end
Visualize execution

When the array does not contain target, \(i\) ultimately points to the first element greater than target, while \(j\) points to the rightmost element smaller than target.

As shown below, we can therefore construct a value absent from the array and use it to find the left and right boundaries.

  • To find the leftmost target, search for target - 0.5 and return pointer \(i\).
  • To find the rightmost target, search for target + 0.5 and return pointer \(j\).

Turning a boundary search into an element search

Figure 10-8   Turning a boundary search into an element search

The code is omitted here, but keep two points in mind.

  • The given array contains no fractional values, so we do not need to handle equality.
  • Since this method introduces fractional values, change the function's target variable to a floating-point type. No change is needed in Python.
Share your insights, questions, or suggestions in the comments