101 Logo
onenoughtone

Boundary Binary Search

What is Boundary Binary Search?

Boundary Binary Search is a pattern used to find the boundary between two regions in a sorted array, such as the first or last occurrence of a value, or the insertion point for a new value.

Unlike standard binary search which returns as soon as it finds a match, boundary binary search continues searching even after finding a match to locate the exact boundary.

Key Variations

  • First Occurrence: Finding the first occurrence of a target value in a sorted array with duplicates
  • Last Occurrence: Finding the last occurrence of a target value in a sorted array with duplicates
  • Insertion Point: Finding the position where a target value should be inserted to maintain the sorted order
  • Peak Element: Finding a peak element in an array (an element greater than its neighbors)

Finding the First Occurrence

Here's how to find the first occurrence of a target value in a sorted array:

function findFirstOccurrence(arr, target) { let left = 0; let right = arr.length - 1; let result = -1; while (left <= right) { const mid = Math.floor((left + right) / 2); // Found a potential result if (arr[mid] === target) { result = mid; // Save this as a potential result right = mid - 1; // Continue searching in the left half } // Target is in the right half else if (arr[mid] < target) { left = mid + 1; } // Target is in the left half else { right = mid - 1; } } return result; }

Finding the Last Occurrence

Here's how to find the last occurrence of a target value in a sorted array:

function findLastOccurrence(arr, target) { let left = 0; let right = arr.length - 1; let result = -1; while (left <= right) { const mid = Math.floor((left + right) / 2); // Found a potential result if (arr[mid] === target) { result = mid; // Save this as a potential result left = mid + 1; // Continue searching in the right half } // Target is in the right half else if (arr[mid] < target) { left = mid + 1; } // Target is in the left half else { right = mid - 1; } } return result; }

Finding the Insertion Point

Here's how to find the position where a target value should be inserted to maintain the sorted order:

function searchInsert(nums, target) { let left = 0; let right = nums.length - 1; while (left <= right) { const mid = Math.floor((left + right) / 2); if (nums[mid] === target) { return mid; } if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } // At this point, left > right // left is the position where target should be inserted return left; }
IntroVisualizePatternsPractice
101 Logo
onenoughtone