knaxuslearn · build · ship

week 3 of 15

Binary search and bit tricks

Get comfortable with these coding mechanics first: computing the middle, choosing between a loop of l <= r and l < r, integer division, bit operators (&, ^, <<, >>). Template to type from memory by the end of the week: binary search on a sorted range, and the same loop over the answer with a feasible(x) check.

  1. 21Binary Search (opens LeetCode in a new tab)Classic templateEasy
    Common mistake
    Setting l = mid, which can loop forever.
  2. 22Search a 2D Matrix (opens LeetCode in a new tab)Binary search on a flattened matrixMedium
    Common mistake
    Dividing by rows instead of cols.
  3. 23Find Minimum in Rotated Sorted Array (opens LeetCode in a new tab)Binary search on a rotated arrayMediumcore
    Common mistake
    Using r = mid - 1, which can skip the minimum.
  4. 24Search in Rotated Sorted Array (opens LeetCode in a new tab)Find the sorted halfMediumcore
    Common mistake
    Using < instead of <= in the sorted-half test.
  5. 25Find Peak Element (opens LeetCode in a new tab)Binary search on the slopeMedium
    Common mistake
    Reading a[mid+1] when mid could be the last index (use l < r).
  6. 26Koko Eating Bananas (opens LeetCode in a new tab)Binary search on the answerMediumcore
    Common mistake
    Float division. Use (p + k - 1) // k.
  7. 27Time Based Key-Value Store (opens LeetCode in a new tab)Binary search inside a design problemMedium
    Common mistake
    Returning the wrong value when no time is <= t. Return an empty string.
  8. 28Single Number (opens LeetCode in a new tab)XOR cancellationEasy
    Common mistake
    There is little to get wrong in the code. Be able to explain why x ^ x = 0.
  9. 29Number of 1 Bits (opens LeetCode in a new tab)Clear the lowest set bitEasy
    Common mistake
    Negative numbers in some languages. Mask to 32 bits.
  10. 30Sum of Two Integers (opens LeetCode in a new tab)Add with XOR and carryMedium
    Common mistake
    Python only: mask to 32 bits because integers never overflow.