Faaez Razeen

Binary Search

  • 2 min read
  • LC-Medium

3 years ago

Template

var search = function(nums, target) { let lo = 0, hi = nums.length - 1; while (lo < hi) { let mid = lo + Math.floor((hi - lo + 1) / 2) if (target < nums[mid]) { hi = mid - 1 } else { lo = mid; } } return nums[lo] == target ? lo : -1; };

Most Generalized Binary Search

Suppose we have a search space. It could be an array, a range, etc. Usually it's sorted in ascend order. For most tasks, we can transform the requirement into the following generalized form:

Minimize k , s.t. condition(k) is True

The following code is the most generalized binary search template:

def binary_search(array) -> int: def condition(value) -> bool: pass left, right = 0, len(array) while left < right: mid = left + (right - left) // 2 if condition(mid): right = mid else: left = mid + 1 return left

What's really nice of this template is that, for most of the binary search problems, we only need to modify three parts after copy-pasting this template, and never need to worry about corner cases and bugs in code any more:

Problems

Easy

Medium

Hard