📓
Algorithms
  • Introduction to Data Structures & Algorithms with Leetcode
  • Strings
    • Dutch Flags Problem
      • List Partitoning
    • Counters
      • Majority Vote
      • Removing Parentheses
      • Remove Duplicates from Sorted Array
    • Maths
      • Lone Integer
      • Pigeonhole
      • Check If N and Its Double Exist
      • Find Numbers with Even Number of Digits
    • Two Pointers
      • Remove Element
      • Replace Elements with Greatest Element on Right Side
      • Valid Mountain Array
      • Sort Array by Parity
      • Squares of a Sorted Array
      • Max Consecutive Ones
    • Sliding Window
      • Max Consecutive Ones 3
    • Stacks
      • Balanced Brackets
    • General Strings & Arrays
      • Move Zeros
      • Unique Elements
      • Merge Sorted Array
    • Matrices
      • Valid Square
      • Matrix Search Sequel
  • Trees
    • Untitled
  • Recursion
    • Introduction
    • Backtracking
      • Permutations
  • Dynamic Programming
    • Introduction
    • Minimum (Maximum) Path to Reach a Target
      • Min Cost Climbing Stairs
      • Coin Change
      • Minimum Path Sum
      • Triangle
      • Minimum Cost to Move Chips to The Same Position
      • Consecutive Characters
      • Perfect Squares
    • Distinct Ways
      • Climbing Stairs
      • Unique Paths
      • Number of Dice Rolls with Target Sum
    • Merging Intervals
      • Minimum Cost Tree From Leaf Values
    • DP on Strings
      • Levenshtein Distance
      • Longest Common Subsequence
  • Binary Search
    • Introduction
      • First Bad Version
      • Sqrt(x)
      • Search Insert Position
    • Advanced
      • KoKo Eating Banana
      • Capacity to Ship Packages within D Days
      • Minimum Number of Days to Make m Bouquets
      • Split array largest sum
      • Minimum Number of Days to Make m Bouquets
      • Koko Eating Bananas
      • Find K-th Smallest Pair Distance
      • Ugly Number 3
      • Find the Smallest Divisor Given a Threshold
      • Kth smallest number in multiplication table
  • Graphs
    • Binary Trees
      • Merging Binary Trees
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Populating Next Right Pointers in Each Node
      • Populating Next Right Pointers in Each Node II
      • 106. Construct Binary Tree from Inorder and Postorder Traversal
      • Serialise and Deserialise a Linked List
      • Maximum Depth of Binary Tree
      • Lowest Common Ancestor of a Binary Tree
    • n-ary Trees
      • Untitled
      • Minimum Height Trees
    • Binary Search Trees
      • Counting Maximal Value Roots in Binary Tree
      • Count BST nodes in a range
      • Invert a Binary Tree
      • Maximum Difference Between Node and Ancestor
      • Binary Tree Tilt
  • Practice
  • Linked Lists
    • What is a Linked List?
    • Add Two Numbers
      • Add Two Numbers 2
    • Reverse a Linked List
    • Tortoise & Hare Algorithm
      • Middle of the Linked List
  • Bitshifting
    • Introduction
  • Not Done Yet
    • Uncompleted
    • Minimum Cost For Tickets
    • Minimum Falling Path Sum
Powered by GitBook
On this page

Was this helpful?

  1. Binary Search

Introduction

PreviousLongest Common SubsequenceNextFirst Bad Version

Last updated 4 years ago

Was this helpful?

Based on this:

Binary Search is an algorithm for searching for data in sorted data.

We split the search space into two halves and only keep the half that probably has the search target and throw away the other half that cannot contain the target.

In this way, we reduce the search sapce to half at every step until we find the target.

Binary search helps us reduce our O(n) linear search algorithm into O(log n).

We often want to implement a slightly modified binary search. Here are some typical problems we may face:

  • When do we exit the loop? Should we use left < right or <= right?

  • How to initialise the boundary variable left and right

  • How to update the boundary? How to choose the appropriate combination from left = mid, left = mid + 1 and right = mid, right = mid - 1?

A rather common misunderstanding of binary search is that people often think this technique could only be used in simple scenario like "Given a sorted array, find a specific value in it". As a matter of fact, it can be applied to much more complicated situations.

After a lot of practice in LeetCode, I've made a powerful binary search template and solved many Hard problems by just slightly twisting this template. I'll share the template with you guys in this post. I don't want to just show off the code and leave. Most importantly, I want to share the logical thinking: how to apply this general template to all sorts of problems. Hopefully, after reading this post, people wouldn't be pissed off any more when LeetCoding, "Holy sh*t! This problem could be solved with binary search! Why didn't I think of that before!"

Generalised 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

This is a generalised binary search.

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:

  • Correctly initialize the boundary variables left and right. Only one rule: set up the boundary to include all possible elements;

  • Decide return value. Is it return left or return left - 1? Remember this: after exiting the while loop, left is the minimal k​ satisfying the condition function;

  • Design the condition function. This is the most difficult and most beautiful part. Needs lots of practice.

Below I'll show you guys how to apply this powerful template to many LeetCode problems.

Loading...LeetCode
Logo