Code Templates
Binary Search
Decision Flow
Interactive Flow with Problem Details (Auto-Layout)
Layout:
📍 Manual Layout (Drag nodes to adjust)
Code Template
Initializing search range
- The element we are looking for is in the range
[left, right). (right is not included.) - Use
<instead of<=to prevent infinite loop when the template range closed on the left, open on the right.
Update search range
- Calculates the
midindex of a search interval to avoid overflow and ensure accurate indexing. - Update the left or right boundary based on the output of
valid(). left: the index of firstvalid()element.
Implenent valid function
- Implenent valid function based on problem requirements.
def lower_bound(nums, target):left, right = 0, len(nums)while left < right:
Use Code Template
class Solution:def mySqrt(self, x):def valid(mid):return mid * mid > xleft = 1right = x + 1while left < right:mid = (left + right) // 2if valid(mid):right = midelse:left = mid + 1# left - 1 is the index of first non valid() elementreturn left - 1
class Solution:def firstBadVersion(self, n):def valid(mid):return isBadVersion(mid)left = 0right = n + 1while left < right:mid = (left + right) // 2if valid(mid):right = midelse:left = mid + 1return left
744. Find Smallest Letter Greater Than Target
class Solution:def nextGreatestLetter(self, letters: List[str], target: str) -> str:def valid(letter):if letter > target:return Truereturn Falseleft, right = 0, len(letters)while left < right:mid = (left + right) // 2if valid(letters[mid]):right = midelse:left = mid + 1return letters[left % len(letters)]
class Solution:def minEatingSpeed(self, piles: List[int], h: int) -> int:def valid(k):hours_needed = 0for pile in piles:hours_needed += (pile + k - 1) // kreturn hours_needed <= hleft, right = 1, max(piles)while left < right:mid = (left + right) // 2if valid(mid):right = midelse:left = mid + 1return left
1011. Capacity To Ship Packages Within D Days
class Solution:def shipWithinDays(self, weights: List[int], days: int) -> int:def valid(capacity):days_needed = 1current_load = 0for weight in weights:if current_laoad + weight > capacity:days_needed += 1current_load = weightelse:current_load += weightreturn days_needed <= daysleft, right = max(weights), sum(weights)while left < right:mid = (left + right) // 2if valid(mid):right = midelse:left = mid + 1return left
1060. Missing Element in Sorted Array
class Solution:def missingElement(self, nums, k):# n of missicg on left of index >= kdef valid(index):missing = nums[index] - (nums[0] + index)if missing >= k:return Truereturn Falseleft, right = 0, len(nums)while left < right:mid = (left + right) // 2if valid(mid):right = midelse:left = mid + 1return nums[0] + left - 1 + k
Common mistakes
- Incorrect Loop Condition
# Wrongwhile left <= right: # the valid range is [left, right) in this template# Correctwhile left < right:
- Incorrect Right Boundary Value
# Wrong: might miss last elementright = len(nums) - 1# Correct: for lower_boundright = len(nums)
- Incorrect Pointer Updates
# Wrong: missing +1 when updating leftif not valid(nums[mid]):left = mid # This can lead to infinite loop# Wrong: adding +1 when updating rightif valid(nums[mid]):right = mid + 1 # This skips potential answer# Correct:if valid(nums[mid], target):right = midelse:left = mid + 1
Issues and consideration
- Custom Comparators: If using custom data types, ensure that the comparator correctly defines the ordering. This is crucial for the accuracy of the binary search.
- Validation: The function will return
0if the target isvalidfor all elements in the array (targetis small than all other elements). The function will returnlen(nums)if the target isnot validfor all elements in the array.