Patterns: searching
This review of searching covers three patterns: binary search works whenever a step can tell which half holds the answer, a row- and column-sorted matrix is searched from the top-right corner, and the data decides between find, lower_bound, set and unordered_map.
Search problems don't test memorised code; they test two things: can each step throw away a big chunk, and which structure suits this data. Three kinds below, each with one pattern.
Pattern one: if you can tell which half, you can binary search
The heart of binary search isn't "the array is sorted" but each step can settle which half the answer is in. The classic example is a rotated sorted array: a sorted array cut somewhere and its two parts swapped, like 4 5 6 7 0 1 2. The whole array isn't sorted, but cut at mid, at least one of the two halves is sorted:
a[lo] <= a[mid]: the left half a[lo..mid] is sorted. If x falls in [a[lo], a[mid]), go left, otherwise right.- Otherwise the right half a[mid..hi] is sorted. If x falls in (a[mid], a[hi]], go right, otherwise left.
lo↑hi↑mid1#include <iostream>2#include <vector>3using namespace std;4 5int search(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size() - 1;7 while (lo <= hi) {8 int mid = lo + (hi - lo) / 2;9 if (a[mid] == x) return mid;10 if (a[lo] <= a[mid]) { // the left half is sorted11 if (a[lo] <= x && x < a[mid]) hi = mid - 1;12 else lo = mid + 1;13 } else { // the right half is sorted14 if (a[mid] < x && x <= a[hi]) lo = mid + 1;15 else hi = mid - 1;16 }17 }18 return -1;19}20 21int main() {22 vector<int> a = {4, 5, 6, 7, 0, 1, 2};23 cout << "1 is at " << search(a, 1) << ", 6 at " << search(a, 6) << ", 3 at " << search(a, 3) << endl;24 return 0;25}
1 is at 5, 6 at 2, 3 at -1
The same idea solves: the minimum of a rotated array, a "peak" (an element bigger than both neighbours), the maximum of an array that rises then falls. None of these has a ready-made STL function: lower_bound only understands "the left part all one kind, the right part all the other", and a rotated array isn't like that.
The rotated array 6 7 1 2 3 4 5, with lo = 0, hi = 6 and mid = 3. Which half is sure to be sorted?
The minimum of a rotated array
✓The array was sorted and then rotated, with no repeats. The minimum is the "rotation point". Look at a[mid] and a[hi]: a[mid] > a[hi] means the rotation point is right of mid, otherwise at mid or left of it.
0 11 1
1#include <iostream>2#include <vector>3using namespace std;4 5int find_min(const vector<int>& a) {6 int lo = 0, hi = (int)a.size() - 1;7 // while lo < hi: mid; a[mid] > a[hi] gives lo = mid + 1, else hi = mid8 return a[lo];9}10 11int main() {12 vector<int> a = {4, 5, 6, 7, 0, 1, 2}, b = {11, 13, 15, 17}, c = {3, 1, 2};13 cout << find_min(a) << " " << find_min(b) << " " << find_min(c) << endl;14 return 0;15}
Find a peak
✓A peak is an element bigger than both its neighbours (beyond either end counts as minus infinity), and neighbouring values are never equal. Look at a[mid] and a[mid + 1]: going uphill there's certainly a peak. Return the index of one peak.
2 0 3
1#include <iostream>2#include <vector>3using namespace std;4 5int peak(const vector<int>& a) {6 int lo = 0, hi = (int)a.size() - 1;7 // while lo < hi: a[mid] < a[mid + 1] means uphill to the right, lo = mid + 1; else hi = mid8 return lo;9}10 11int main() {12 vector<int> a = {1, 3, 5, 4, 2}, b = {9, 7, 3}, c = {1, 2, 3, 4};13 cout << peak(a) << " " << peak(b) << " " << peak(c) << endl;14 return 0;15}
Pattern two: in two dimensions, find a corner that rules out a whole row
A matrix increases left to right along each row and top to bottom down each column; find x. Start at the top-right corner: it's the biggest in its row and the smallest in its column.
- Bigger than x: everything below it in the column is bigger still, rule out the column, go left.
- Smaller than x: everything left of it in the row is smaller still, rule out the row, go down.
Each step rules out a row or a column, so an m × n matrix takes at most m + n steps. Starting at the top-left doesn't work: right and down both get bigger, so you can't tell which way to go. In C++ the matrix is a vector<vector<int>>: m.size() is the number of rows, m[0].size() the number of columns.
In the same matrix, starting from the top-right corner, you look for 13. Which numbers do you look at, in order?
A matrix sorted by rows and columns
✓Start at the top-right corner: bigger than x, go left; smaller, go down; equal, found. Print how many steps it took (cells looked at) and whether it was found.
5 found, looked at 5 20 not found, looked at 5
1#include <iostream>2#include <vector>3using namespace std;4 5vector<vector<int>> m = {6 {1, 4, 7, 11, 15},7 {2, 5, 8, 12, 19},8 {3, 6, 9, 16, 22},9 {10, 13, 14, 17, 24},10};11 12void find(int x) {13 int rows = (int)m.size(), r = 0, c = (int)m[0].size() - 1, steps = 0;14 // while r < rows and c >= 0: steps++; equal: print and return; bigger than x: c--, else r++15 cout << x << " not found, looked at " << steps << endl;16}17 18int main() {19 find(5);20 find(20);21 return 0;22}
Pattern three: which search for which data
| What the data is like | Use | Search |
|---|---|---|
| unsorted, searched rarely | sequential search | O(n) |
| a sorted array, rarely changed | binary search | O(log n) |
| inserted and deleted often, still sorted | a balanced tree (AVL, red-black) | O(log n) |
| on disk, a lot of it | a B+ tree | 2 to 4 disk reads |
| looked up by "equal" only, no order needed | a hash table (chapter 3) | O(1) on average |
In exams: multiple-choice questions often ask "which search needs sorted data" (binary, and block search between blocks) and "which works only on sequential storage" (binary); a decision tree and ASL calculation turns up almost every year, so keep successful and unsuccessful apart.
A phone's contacts: look someone up by exact name, add and delete people often, never list them in order. What fits best?
What does binary search need from the data?
Two exam calculations: unsuccessful ASL and block search
Search calculation questions all ask "how many comparisons on average", the average search length, ASL. These two come up most:
- The unsuccessful ASL: put a "failure node" in every empty spot of the decision tree, n + 1 of them for n elements; an unsuccessful search makes as many comparisons as the failure node's parent's level; average those.
- Block search (indexed sequential search): split n values into b blocks, unsorted inside each block but sorted from block to block, with an index of "the largest in each block". Find the block in the index first, then search the block sequentially. With s values a block and the index searched sequentially, ASL = (b + 1) / 2 + (s + 1) / 2, smallest when s = √n.
Binary search (mid = (lo + hi) / 2) on the sorted list 10 20 30 40 50. What is the ASL of an unsuccessful search?
100 numbers in 10 blocks of 10, with sequential search both in the index and inside a block. What is the ASL of a successful search?
With the STL
The table in pattern three, in C++, is a choice of container:
| What the data is like | In C++ | One search | One change |
|---|---|---|---|
| unsorted, searched once or twice | find(v.begin(), v.end(), x) | O(n) | push_back O(1) |
| read in first, then only searched | sort once, then binary_search / lower_bound | O(log n) | O(n): it moves things |
| changed and searched as you go, order or ranges needed | set / map, the member lower_bound | O(log n) | O(log n) |
| looked up by "equal" only | unordered_set / unordered_map | O(1) on average | O(1) on average |
A sorted vector and a set both search in O(log n); the difference is in changing them: insert a value into the middle of a sorted vector and everything after it moves back. Insert the same 500 random values one by one into each and count the work:
1#include <iostream>2#include <vector>3#include <set>4#include <algorithm>5#include <random>6using namespace std;7 8long cmps = 0;9 10struct CountLess {11 bool operator()(int a, int b) const {12 cmps++;13 return a < b;14 }15};16 17int main() {18 mt19937 g(42);19 uniform_int_distribution<int> d(1, 100000);20 vector<int> v;21 set<int, CountLess> s;22 long moves = 0;23 for (int i = 0; i < 500; i++) {24 int x = d(g);25 auto pos = lower_bound(v.begin(), v.end(), x);26 moves += v.end() - pos; // inserting at pos moves this many back one27 v.insert(pos, x);28 s.insert(x);29 }30 cout << "sorted vector: " << moves << " moves" << endl;31 cout << "set: " << cmps << " comparisons" << endl;32 33 auto a = lower_bound(v.begin(), v.end(), 50000);34 auto b = s.lower_bound(50000);35 cout << "the first >= 50000: " << *a << " and " << *b << endl;36 return 0;37}
sorted vector: 58029 moves set: 4910 comparisons the first >= 50000: 50264 and 50264
With 500 values the vector made over 58 000 moves, close to n² / 4 ≈ 62 500; each set insert walks just one path ten or so levels deep, under 5000 comparisons in all. When the data doesn't change it's the other way round: a sorted vector keeps its elements side by side and uses less memory than a set (each set node also stores three pointers and a colour), and its binary search is faster too. First settle whether the data will change, then pick the container.
In interviews: asked "why this container?", answer from this table: is order needed (no: hash), will it change (no: sorted vector), then the cost of each operation. unordered_map is O(1) on average but O(n) at worst, and its iteration order isn't fixed; map is a steady O(log n), and iterates smallest first.
You read in 100,000 numbers that never change afterwards, then answer 100,000 questions "what is the first value ≥ x?". What suits best?
vector uses the least memory too. A hash table can only answer "equal to"; find each time is O(n); a set would work, but through the member s.lower_bound(x), since std::lower_bound on a set is O(n).Summary
Three search patterns
- If you can tell which half holds the answer, binary search: rotated arrays, minimum, peak
- A matrix sorted both ways: walk from the top-right, ruling out a row or column a step, O(m + n)
- Unsorted: find; sorted and unchanging: vector with lower_bound; changing: set / map; equality only: unordered_map
- Unsuccessful ASL: the failure node's parent; block search is best at s = √n
1while (lo < hi) {2 int mid = lo + (hi - lo) / 2;3 if (answer is to the right) lo = mid + 1;4 else hi = mid;5}
Chapter 6 quick check
5 questions: the sentinel, binary search comparisons, bounds, binary search on the answer and balanced trees. Work out what each prints first, then pick.
Sequential search with a sentinel, from the back, for 8: what does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {0, 8, 3, 8, 5, 1}; // data in a[1..5]7 int x = 8, i = 5;8 a[0] = x;9 while (a[i] != x) i--;10 cout << i << endl;11 return 0;12}
Binary searching 7 values for 25, which isn't there: how many comparisons before it knows?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {10, 20, 30, 40, 50, 60, 70};7 int lo = 0, hi = 6, x = 25, cmp = 0;8 while (lo <= hi) {9 int mid = lo + (hi - lo) / 2;10 cmp++;11 if (a[mid] == x) break;12 if (a[mid] < x) lo = mid + 1;13 else hi = mid - 1;14 }15 cout << cmp << endl;16 return 0;17}
lower_bound and upper_bound for 2 in 1 2 2 2 3 5: what does it print?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> a = {1, 2, 2, 2, 3, 5};8 auto lo = lower_bound(a.begin(), a.end(), 2);9 auto hi = upper_bound(a.begin(), a.end(), 2);10 cout << lo - a.begin() << " " << hi - a.begin() << " " << hi - lo << endl;11 return 0;12}
Binary search on the answer: the first positive integer whose cube is at least 50, and how many rounds?
1#include <iostream>2using namespace std;3 4int main() {5 int lo = 1, hi = 100, rounds = 0;6 while (lo < hi) {7 int mid = lo + (hi - lo) / 2;8 rounds++;9 if (mid * mid * mid >= 50) hi = mid;10 else lo = mid + 1;11 }12 cout << lo << " " << rounds << endl;13 return 0;14}
An AVL tree of height h has at least N(h) = N(h − 1) + N(h − 2) + 1 nodes. At least how many for height 5?
1#include <iostream>2using namespace std;3 4int main() {5 int n[8] = {0, 1, 2};6 for (int h = 3; h <= 6; h++)7 n[h] = n[h - 1] + n[h - 2] + 1;8 cout << n[5] << endl;9 return 0;10}