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.
- 21Binary Search (opens LeetCode in a new tab)Classic templateEasy
- Common mistake
- Setting l = mid, which can loop forever.
- 22Search a 2D Matrix (opens LeetCode in a new tab)Binary search on a flattened matrixMedium
- Common mistake
- Dividing by rows instead of cols.
- 23Find Minimum in Rotated Sorted Array (opens LeetCode in a new tab)Binary search on a rotated arrayMedium
- Common mistake
- Using r = mid - 1, which can skip the minimum.
- 24Search in Rotated Sorted Array (opens LeetCode in a new tab)Find the sorted halfMedium
- Common mistake
- Using < instead of <= in the sorted-half test.
- 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).
- 26Koko Eating Bananas (opens LeetCode in a new tab)Binary search on the answerMedium
- Common mistake
- Float division. Use (p + k - 1) // k.
- 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.
- 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.
- 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.
- 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.