A.1.1.1: Binary Search

Learning Objectives

  1. Understand conceptually how binary search works

  2. Know how to implement binary search in code

Introduction

Binary search allows us to search a sorted array for a target number in O(logn) time. The following videos explain the concept.

Dramatic illustration of the efficiency of binary search
Explanation of the binary search algorithm in code and its runtime

Example Code

Consider the following canonical binary search implementation.

Exercises

After attempting each problem, find solutions in the Leaderboard tab (HackerRank, may be on left side of page) or Solution or Discuss tabs (LeetCode) on that problem's page. If you get stuck for more than 15 minutes, review and understand the solutions and move on. Come back and re-attempt the problem after a few days.

Pre-Class

  1. Binary Search (LeetCode)

Part 1

  1. First Bad Version (LeetCode)

  2. Valid Perfect Square (LeetCode)

  3. Search Insert Position (LeetCode)

  4. Two Sum II Input Array is Sorted (LeetCode)

  5. Count Negative Numbers in a Sorted Matrix (LeetCode)