Skip to content

10.2   Finding an insertion point with binary search

Binary search can do more than find a target element. It also solves many variations of the problem, such as finding where to insert a target.

10.2.1   When there are no duplicates

Question

Given a sorted array nums of length \(n\) with no duplicate elements and a value target, insert target into nums while preserving its order. If target is already present, insert the new value to its left. Return the index of the newly inserted target, as illustrated below.

Figure 10-4   Example data for finding an insertion point

Description of Figure 10-4: Insertion position in a sorted array

Insert an equal new value to the left of the existing element while keeping the array sorted.

The initial duplicate-free sorted array is nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35], and the target element to insert is target = 6. By convention, the array remains sorted after insertion; if an element equal to target is already present, the new element is inserted to the left of that equal element.

The upper row displays the original array nums, with an upward arrow labeled “Insertion point” beneath the gap between element 3 (index 1) and the existing element 6 (index 2), indicating that the insertion index for target is 2.

Below a thick downward arrow labeled “Insert target” in the middle, the lower row displays the resulting 11-element array [1, 3, 6, 6, 8, 12, 15, 23, 26, 31, 35]: the cyan-highlighted 6 is the newly inserted element at index 2, while the original green 6 and every element to its right are shifted one position to the right, moving the original 6 to index 3.

Because the initial array in this example has no duplicates, the index of the existing target is itself the insertion point; equal elements may appear after insertion.

To reuse the binary search code from the previous section, we need to answer two questions.

Question 1: If the array contains target, is the insertion index the index of that element?

The problem asks us to insert target to the left of the equal element, so the new target takes the original one's position. Thus, if the array contains target, the insertion index is the index of that target.

Question 2: If the array does not contain target, which index is the insertion point?

Consider the search process more closely. Pointer \(i\) moves when nums[m] < target, so \(i\) approaches elements greater than or equal to target. Similarly, pointer \(j\) keeps approaching elements less than or equal to target.

When the search ends, \(i\) points to the first element greater than target, and \(j\) points to the rightmost element smaller than target. Thus, when target is absent, the insertion index is \(i\). The code is as follows:

binary_search_insertion.py
def binary_search_insertion_simple(nums: list[int], target: int) -> int:
    """Find an insertion point using binary search (no duplicates)"""
    i, j = 0, len(nums) - 1  # Initialize the closed interval [0, n-1]
    while i <= j:
        m = (i + j) // 2  # Calculate the midpoint index m
        if nums[m] < target:
            i = m + 1  # Target must be in [m+1, j] if it exists
        elif nums[m] > target:
            j = m - 1  # Target must be in [i, m-1] if it exists
        else:
            return m  # Target was found; return insertion point m
    # Target was not found; return insertion point i
    return i
binary_search_insertion.cpp
/* Find an insertion point using binary search (no duplicates) */
int binarySearchInsertionSimple(vector<int> &nums, int target) {
    int i = 0, j = nums.size() - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m; // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i;
}
binary_search_insertion.java
/* Find an insertion point using binary search (no duplicates) */
int binarySearchInsertionSimple(int[] nums, int target) {
    int i = 0, j = nums.length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m; // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i;
}
binary_search_insertion.cs
/* Find an insertion point using binary search (no duplicates) */
int BinarySearchInsertionSimple(int[] nums, int target) {
    int i = 0, j = nums.Length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m; // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i;
}
binary_search_insertion.go
/* Find an insertion point using binary search (no duplicates) */
func binarySearchInsertionSimple(nums []int, target int) int {
    // Initialize the closed interval [0, n-1]
    i, j := 0, len(nums)-1
    for i <= j {
        // Calculate the midpoint index m
        m := i + (j-i)/2
        if nums[m] < target {
            // Target must be in [m+1, j] if it exists
            i = m + 1
        } else if nums[m] > target {
            // Target must be in [i, m-1] if it exists
            j = m - 1
        } else {
            // Target was found; return insertion point m
            return m
        }
    }
    // Target was not found; return insertion point i
    return i
}
binary_search_insertion.swift
/* Find an insertion point using binary search (no duplicates) */
func binarySearchInsertionSimple(nums: [Int], target: Int) -> Int {
    // Initialize the closed interval [0, n-1]
    var i = nums.startIndex
    var j = nums.endIndex - 1
    while i <= j {
        let m = i + (j - i) / 2 // Calculate the midpoint index m
        if nums[m] < target {
            i = m + 1 // Target must be in [m+1, j] if it exists
        } else if nums[m] > target {
            j = m - 1 // Target must be in [i, m-1] if it exists
        } else {
            return m // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i
}
binary_search_insertion.js
/* Find an insertion point using binary search (no duplicates) */
function binarySearchInsertionSimple(nums, target) {
    let i = 0,
        j = nums.length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, using Math.floor() to round down
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m; // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i;
}
binary_search_insertion.ts
/* Find an insertion point using binary search (no duplicates) */
function binarySearchInsertionSimple(
    nums: Array<number>,
    target: number
): number {
    let i = 0,
        j = nums.length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, using Math.floor() to round down
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m; // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i;
}
binary_search_insertion.dart
/* Find an insertion point using binary search (no duplicates) */
int binarySearchInsertionSimple(List<int> nums, int target) {
  int i = 0, j = nums.length - 1; // Initialize the closed interval [0, n-1]
  while (i <= j) {
    int m = i + (j - i) ~/ 2; // Calculate the midpoint index m
    if (nums[m] < target) {
      i = m + 1; // Target must be in [m+1, j] if it exists
    } else if (nums[m] > target) {
      j = m - 1; // Target must be in [i, m-1] if it exists
    } else {
      return m; // Target was found; return insertion point m
    }
  }
  // Target was not found; return insertion point i
  return i;
}
binary_search_insertion.rs
/* Find an insertion point using binary search (no duplicates) */
fn binary_search_insertion_simple(nums: &[i32], target: i32) -> i32 {
    let (mut i, mut j) = (0, nums.len() as i32 - 1); // Initialize the closed interval [0, n-1]
    while i <= j {
        let m = i + (j - i) / 2; // Calculate the midpoint index m
        if nums[m as usize] < target {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if nums[m as usize] > target {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m;
        }
    }
    // Target was not found; return insertion point i
    i
}
binary_search_insertion.c
/* Find an insertion point using binary search (no duplicates) */
int binarySearchInsertionSimple(int *nums, int numSize, int target) {
    int i = 0, j = numSize - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            return m; // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i;
}
binary_search_insertion.kt
/* Find an insertion point using binary search (no duplicates) */
fun binarySearchInsertionSimple(nums: IntArray, target: Int): Int {
    var i = 0
    var j = nums.size - 1 // Initialize the closed interval [0, n-1]
    while (i <= j) {
        val m = i + (j - i) / 2 // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1 // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1 // Target must be in [i, m-1] if it exists
        } else {
            return m // Target was found; return insertion point m
        }
    }
    // Target was not found; return insertion point i
    return i
}
binary_search_insertion.rb
### Find an insertion point using binary search (no duplicates) ###
def binary_search_insertion_simple(nums, target)
  # Initialize the closed interval [0, n-1]
  i, j = 0, nums.length - 1

  while i <= j
    # Calculate the midpoint index m
    m = (i + j) / 2

    if nums[m] < target
      i = m + 1 # Target must be in [m+1, j] if it exists
    elsif nums[m] > target
      j = m - 1 # Target must be in [i, m-1] if it exists
    else
      return m  # Target was found; return insertion point m
    end
  end

  i # Target was not found; return insertion point i
end
Visualize execution

10.2.2   When duplicates are present

Question

Modify the previous problem to allow duplicate elements in the array. All other requirements remain the same.

If the array contains multiple occurrences of target, ordinary binary search can return the index of one occurrence, but cannot determine how many more occurrences lie to its left or right.

The target must be inserted as far left as possible, so we need the index of the leftmost target. One initial approach follows the steps below.

  1. Run binary search to find the index of any target, denoted by \(k\).
  2. Starting at index \(k\), scan leftward and return when the leftmost target is reached.

Figure 10-5   Finding the insertion point among duplicates with a linear scan

Description of Figure 10-5: Scanning left after a binary search match

First find one occurrence of the target with ordinary binary search, then scan left linearly to locate the leftmost position.

The sorted array is nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15] (0-indexed), and the search target is target = 6. Five duplicate 6s occupy indices 2 through 6 consecutively, and the insertion rule requires placing a new 6 to the left of all existing 6s.

The figure illustrates this initial approach in two steps: first, “1. First use binary search to find any 6,” where ordinary binary search hits the orange cell at index 4 (marked with pointer k), though this match alone cannot tell how many equal 6s lie to its left.

Second, “2. Then scan left to find the leftmost 6”: starting from index k = 4, two curved blue arrows beneath the array step leftward one cell at a time, passing the 6 at index 3 and reaching the blue-highlighted cell 6 at index 2. Because the element further left at index 1 is 3 (less than 6), index 2 is the leftmost 6 and therefore the desired insertion point.

Scanning left linearly can take O(n) time when there are many duplicates, degrading worst-case complexity; modifying binary search directly preserves O(log n) time.

Although this works, it includes a linear search and therefore takes \(O(n)\) time. It is inefficient when the array contains many occurrences of target.

Now consider extending binary search itself. As shown below, the overall process remains the same: each round calculates midpoint index \(m\) and compares target with nums[m]. The cases are as follows.

  • If nums[m] < target or nums[m] > target, we have not found target. Narrow the interval as in ordinary binary search, bringing pointers \(i\) and \(j\) closer to target.
  • If nums[m] == target, elements smaller than target lie in \([i, m - 1]\). Narrow the interval by setting \(j = m - 1\), bringing pointer \(j\) closer to elements smaller than target.

When the loop finishes, \(i\) points to the leftmost target, and \(j\) points to the rightmost element smaller than target. Index \(i\) is therefore the insertion point.

Figure 10-6   Steps for finding an insertion point among duplicates

Description of Figure 10-6: Finding the leftmost insertion point with binary search

Keep searching leftward when the midpoint equals the target so as to locate the insertion position before all equal elements.

Given the ascending array [1, 3, 6, 6, 6, 6, 6, 10, 12, 15] indexed from 0 to 9, find the insertion point for target = 6. Value 6 occupies indices 2 through 6 consecutively; the problem asks for the index where a new 6 should be inserted so that it appears to the left of all existing 6s (this algorithm only computes and returns the insertion index without actually inserting or shifting elements in the array).

Pointers i and j mark the left and right boundaries of the closed search interval [i, j], and the midpoint index is computed as m = (i + j) / 2 rounded down. When nums[m] < target, set i = m + 1 to advance rightward; when nums[m] > target or nums[m] == target, set j = m - 1 to narrow leftward, keeping pointer j approaching the rightmost element smaller than target and pointer i approaching the first position greater than or equal to target.

Each round first computes the midpoint and then moves one boundary. Right after a boundary is updated, m in the figure still shows the previous midpoint and may lie outside the new interval; m is updated only when the midpoint is recomputed.

Below, the fixed input is listed first, followed by a table summarizing the pointer trace across all eight frames, and then step-by-step notes explaining the reason for each action and the resulting state. The eight frames correspond to three rounds of midpoint comparison, not eight loop iterations.

Fixed input: target value 6
IndexValue
01
13
26
36
46
56
66
710
812
915
Eight-step pointer trace for the leftmost insertion point
StepijmSearch intervalMidpoint or return status
109Not yet computed[0, 9]Not yet computed
2094[0, 9]Midpoint for this round
3034[0, 3]Old midpoint, outside the new interval to the right
4031[0, 3]Midpoint for this round
5231[2, 3]Old midpoint, outside the new interval to the left
6232[2, 3]Midpoint for this round
7212[2, 1], empty intervalOld midpoint; interval is empty, not recomputed
82No longer shown in figureNo longer shown in figureSearch completeOnly returned pointer i is shown
  1. Initialize the search interval

    The target value is 6. Initialize i = 0 and j = 9 so that the closed interval [0, 9] covers all ten elements, with m not yet computed; for the array, see “Fixed input: target value 6.”

  2. Compute midpoint 4

    Round 1: with i = 0 and j = 9, compute m = (0 + 9) // 2 = 4 on interval [0, 9]. nums[4] = 6 equals the target, but we cannot yet tell whether it is the leftmost 6.

  3. Encounter 6, move right boundary left

    nums[4] = 6 equals the target; to check whether more 6s lie to the left, execute j = m - 1. Now i = 0 and j = 3, giving interval [0, 3]; m = 4 in the figure is the unrecomputed old midpoint, left outside the new interval to its right.

  4. Compute midpoint 1

    Round 2: with i = 0 and j = 3, recompute m = (0 + 3) // 2 = 1 on interval [0, 3]. nums[1] = 3 is less than target 6, so the insertion point lies to its right.

  5. Encounter 3, move left boundary right

    Because nums[1] = 3 is less than target 6, execute i = m + 1. Now i = 2 and j = 3, giving interval [2, 3]; m = 1 in the figure is the unrecomputed old midpoint, left outside the new interval to its left.

  6. Compute midpoint 2

    Round 3: with i = 2 and j = 3, recompute m = (2 + 3) // 2 = 2 on interval [2, 3]. nums[2] = 6 again equals the target.

  7. Encounter 6 again, interval becomes empty

    Because nums[2] = 6 equals the target, again execute j = m - 1. Now i = 2 and j = 1, so the closed interval [2, 1] is empty and the loop is about to end; the figure still keeps old midpoint m = 2 without recomputing it.

  8. Return leftmost insertion index 2

    The loop ends, and the figure keeps only the returned pointer i = 2 while hiding j and m. Index 2 is where a new 6 would go, before all five existing 6s; no insertion or element shifting takes place in the original array.

In the code below, the branches for nums[m] > target and nums[m] == target perform the same operation, so they can be combined.

Even so, we can leave them separate to make the logic clearer and easier to read.

binary_search_insertion.py
def binary_search_insertion(nums: list[int], target: int) -> int:
    """Find an insertion point using binary search (with duplicates)"""
    i, j = 0, len(nums) - 1  # Initialize the closed interval [0, n-1]
    while i <= j:
        m = (i + j) // 2  # Calculate the midpoint index m
        if nums[m] < target:
            i = m + 1  # Target must be in [m+1, j] if it exists
        elif nums[m] > target:
            j = m - 1  # Target must be in [i, m-1] if it exists
        else:
            j = m - 1  # Continue in [i, m-1] to find the rightmost element smaller than target
    # Return insertion point i
    return i
binary_search_insertion.cpp
/* Find an insertion point using binary search (with duplicates) */
int binarySearchInsertion(vector<int> &nums, int target) {
    int i = 0, j = nums.size() - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue searching [i, m-1] for the insertion point before any equal elements
        }
    }
    // Return insertion point i
    return i;
}
binary_search_insertion.java
/* Find an insertion point using binary search (with duplicates) */
int binarySearchInsertion(int[] nums, int target) {
    int i = 0, j = nums.length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i;
}
binary_search_insertion.cs
/* Find an insertion point using binary search (with duplicates) */
int BinarySearchInsertion(int[] nums, int target) {
    int i = 0, j = nums.Length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i;
}
binary_search_insertion.go
/* Find an insertion point using binary search (with duplicates) */
func binarySearchInsertion(nums []int, target int) int {
    // Initialize the closed interval [0, n-1]
    i, j := 0, len(nums)-1
    for i <= j {
        // Calculate the midpoint index m
        m := i + (j-i)/2
        if nums[m] < target {
            // Target must be in [m+1, j] if it exists
            i = m + 1
        } else if nums[m] > target {
            // Target must be in [i, m-1] if it exists
            j = m - 1
        } else {
            // Continue in [i, m-1] to find the rightmost element smaller than target
            j = m - 1
        }
    }
    // Return insertion point i
    return i
}
binary_search_insertion.swift
/* Find an insertion point using binary search (with duplicates) */
func binarySearchInsertion(nums: [Int], target: Int) -> Int {
    // Initialize the closed interval [0, n-1]
    var i = nums.startIndex
    var j = nums.endIndex - 1
    while i <= j {
        let m = i + (j - i) / 2 // Calculate the midpoint index m
        if nums[m] < target {
            i = m + 1 // Target must be in [m+1, j] if it exists
        } else if nums[m] > target {
            j = m - 1 // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1 // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i
}
binary_search_insertion.js
/* Find an insertion point using binary search (with duplicates) */
function binarySearchInsertion(nums, target) {
    let i = 0,
        j = nums.length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, using Math.floor() to round down
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i;
}
binary_search_insertion.ts
/* Find an insertion point using binary search (with duplicates) */
function binarySearchInsertion(nums: Array<number>, target: number): number {
    let i = 0,
        j = nums.length - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, using Math.floor() to round down
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i;
}
binary_search_insertion.dart
/* Find an insertion point using binary search (with duplicates) */
int binarySearchInsertion(List<int> nums, int target) {
  int i = 0, j = nums.length - 1; // Initialize the closed interval [0, n-1]
  while (i <= j) {
    int m = i + (j - i) ~/ 2; // Calculate the midpoint index m
    if (nums[m] < target) {
      i = m + 1; // Target must be in [m+1, j] if it exists
    } else if (nums[m] > target) {
      j = m - 1; // Target must be in [i, m-1] if it exists
    } else {
      j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
    }
  }
  // Return insertion point i
  return i;
}
binary_search_insertion.rs
/* Find an insertion point using binary search (with duplicates) */
pub fn binary_search_insertion(nums: &[i32], target: i32) -> i32 {
    let (mut i, mut j) = (0, nums.len() as i32 - 1); // Initialize the closed interval [0, n-1]
    while i <= j {
        let m = i + (j - i) / 2; // Calculate the midpoint index m
        if nums[m as usize] < target {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if nums[m as usize] > target {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue searching [i, m-1] for the insertion point before any equal elements
        }
    }
    // Return insertion point i
    i
}
binary_search_insertion.c
/* Find an insertion point using binary search (with duplicates) */
int binarySearchInsertion(int *nums, int numSize, int target) {
    int i = 0, j = numSize - 1; // Initialize the closed interval [0, n-1]
    while (i <= j) {
        int m = i + (j - i) / 2; // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1; // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1; // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i;
}
binary_search_insertion.kt
/* Find an insertion point using binary search (with duplicates) */
fun binarySearchInsertion(nums: IntArray, target: Int): Int {
    var i = 0
    var j = nums.size - 1 // Initialize the closed interval [0, n-1]
    while (i <= j) {
        val m = i + (j - i) / 2 // Calculate the midpoint index m
        if (nums[m] < target) {
            i = m + 1 // Target must be in [m+1, j] if it exists
        } else if (nums[m] > target) {
            j = m - 1 // Target must be in [i, m-1] if it exists
        } else {
            j = m - 1 // Continue in [i, m-1] to find the rightmost element smaller than target
        }
    }
    // Return insertion point i
    return i
}
binary_search_insertion.rb
### Find an insertion point using binary search (with duplicates) ###
def binary_search_insertion(nums, target)
  # Initialize the closed interval [0, n-1]
  i, j = 0, nums.length - 1

  while i <= j
    # Calculate the midpoint index m
    m = (i + j) / 2

    if nums[m] < target
      i = m + 1 # Target must be in [m+1, j] if it exists
    elsif nums[m] > target
      j = m - 1 # Target must be in [i, m-1] if it exists
    else
      j = m - 1 # Continue in [i, m-1] to find the rightmost element smaller than target
    end
  end

  i # Return insertion point i
end
Visualize execution

Tip

All the code in this section uses closed intervals. Interested readers can implement versions using left-closed, right-open intervals.

Viewed more broadly, binary search simply assigns a search goal to each of pointers \(i\) and \(j\). The goal may be a particular element, such as target, or a range of elements, such as those smaller than target.

As the interval is repeatedly halved, pointers \(i\) and \(j\) approach their assigned goals. Eventually they either find the answer or stop after crossing a boundary.

Share your insights, questions, or suggestions in the comments