Binary Search algorithm

This tutorial is a part of the Data Structures and Algorithms class:

A typical problem solved by Binary Search algorithm

  • Binary in this context means: there are only 2 options.
  • Binary Search drops half of the data points in every iteration, hence CPU performant.

binary search algo

lecture-20/find-65.js
// Given `sorted array` of integers, find the index of number `65`
const arr = [1, 2, 4, 7, 9, 15, 21, 23, 34, 42, 48, 59, 60, 65, 70]
const num = 65

const find = (arr, num) => {
  let result = 'does not exist'
  let left = 0
  let right = arr.length - 1

  while(left <= right) {
    let mid = Math.ceil((left + right) / 2)

    console.log('left:', left, ', mid:', mid, ', right:', right)
    console.log(arr[left], arr[mid], arr[right])

    if(arr[mid] === num) { // found, stop and return result
      result = mid
      break
    } else if(arr[mid] < num) { // continue with data points on the right
      left = mid + 1
    } else if(arr[mid] > num) { // continue with data points on the left
      right = mid - 1
    }
  }

  return result
}

// Time complexity: Binary Search drops half data point in each iteration
// -> Time: O(logn)
console.log(`index of '${num}':`, find(arr, num))
$ node find-65.js
left: 0 , mid: 7 , right: 14
1 23 70
left: 8 , mid: 11 , right: 14
34 59 70
left: 12 , mid: 13 , right: 14
60 65 70
index of '65': 13
Problem Input characteristics Algorithm Time Complexity
Search for a number - sorted array or balanced BST
- known direction
Binary Search O(logn)

check double

lecture-20/check-double.js
// Given an array, check if a number `n` and its double `2n` exist

const checkDouble = (arr) => {
  arr.sort((a,b) => a - b)
  let result = false
  
  // pick the 1st number with For Loop
  for(let i = 0; i < arr.length; i++) {
    
    const double = arr[i] * 2 // ex: 2 -> 2x of 2 = 4, [2, 4]
    const half = arr[i] / 2 // ex: -2 -> 2x of -2 = -4, [-4, -2]

    let left = i + 1
    let right = arr.length - 1

    // pick the 2nd number with Binary Search
    while(left <= right) {
      let mid = Math.ceil((left + right) / 2)

      console.log('left:', left, ', mid:', mid, ', right:', right)
      console.log(arr[left], arr[mid], arr[right])

      if(arr[mid] === double || arr[mid] === half) {
        result = true
        break
      } else if(arr[mid] < double || arr[mid] < half) {
        left = mid + 1
      } else if(arr[mid] > double || arr[mid] > half) {
        right = mid - 1
      }
    }
  }
  
  return result
};

// Time complexity: Binary Search nested in For Loop
// -> Time: O(nlogn)

console.log(checkDouble([10, 2, 5, 3, 7]))
$ node check-double.js
left: 1 , mid: 3 , right: 4
3 7 10
left: 1 , mid: 2 , right: 2
3 5 5
left: 1 , mid: 1 , right: 1
3 3 3
left: 2 , mid: 3 , right: 4
5 7 10
left: 2 , mid: 2 , right: 2
5 5 5
left: 3 , mid: 4 , right: 4
7 10 10
left: 4 , mid: 4 , right: 4
10 10 10
true

Summary

Prob. class P. sub-class Input characteristics Algorithm Time
Complexity
(almost) ANY problem class array, matrix, ... Brute Force O(n) & up
1. Maximization
2. Minimization
3. Find all options array, matrix, ... Brute Force O(n) & up
4. Find most optimal solution
5. Find a truth search for a number - sorted array
or balanced BST
Binary Search O(logn)

Real life interview questions

  1. What are the characteristics of a problem which can be solved by Binary Search?
  2. What is the Time Complexity of Binary Search algorithm? Prove it by counting.
  3. Leetcode #268: Missing Number
  4. Leetcode #2089: Find Target Indices After Sorting Array
  5. Leetcode #1351: Count Negative Numbers in a Sorted Matrix
  6. Leetcode #852: Peak Index in a Mountain Array
  7. Leetcode #540: Single Element in a Sorted Array
  8. Leetcode #1011: Capacity To Ship Packages Within D Days
  9. Leetcode #1346: Check If N and Its Double Exist
  10. Write and function root(x, n) to find root n-th of x with precision 0.0001. Example: root(4, 2) = 2.
  11. Solve all problems above, including the two from the tutorial with recursion.
  12. More on Leetcode #binary-search. Progress check: you should be fairly comfortable doing any of problems in related subject after finishing all problems above.