Exercises: Divide and Conquer
These exercises review the lessons of the chapter, from the divide and conquer scheme to majority, mode and median. Try each one before reading its solution: the solutions are grouped at the end of the page.
Analysis
4.1. Apply the formulas. Give the complexity of each recurrence, identifying , and and the scheme (division or subtraction):
- (a)
- (b)
- (c)
- (d)
- (e)
- (f)
4.2. Strassen. The classic multiplication of two matrices performs multiplications. Splitting each matrix into four blocks of size , the product needs 8 block products and some additions, . Strassen found how to do it with 7 block products (and more additions, still ). Give the complexity of both divide and conquer versions. For , how many scalar multiplications does each one perform, if the recursion goes down to blocks?
Designing divide and conquer algorithms
4.3. Counting inversions. An inversion of an array is a pair of positions with . The number of inversions measures how far an array is from being sorted (it is used, for example, to compare two rankings). Brute force counts them in . Design an algorithm. Hint: modify Mergesort.
4.4. A peak. A peak of an array is a position whose element is not smaller than its neighbors (the elements at the ends have only one neighbor). Every non-empty array has at least one peak. Find one in .
4.5. A rotated array. A sorted array of distinct integers has been rotated: for example 15 18 22 3 7 9 comes from 3 7 9 15 18 22. Find the minimum in . Does your algorithm still work if the elements may be repeated?
4.6. Integer square root. Compute for a long using only integer arithmetic, in steps. How many iterations does your algorithm need for ?
4.7. The counterfeit coin. Among coins that look identical, exactly one is counterfeit and lighter than the others. You have a two-pan balance. Design an algorithm that finds the counterfeit coin with as few weighings as possible. How many weighings does it need for 27 coins? And for 1,000?
4.8. Median of two arrays. Two sorted arrays a and b have elements each. Find the median of the elements (take the smaller of the two central elements) in , without merging them.
Solutions
4.1.
- (a) Division, , , : , so .
- (b) Division, , , : , so .
- (c) Division, , , : , so . The work at the root dominates: .
- (d) Division, , , : , so . The formula also works with non-integer .
- (e) Subtraction, , , : .
- (f) Subtraction, , : , exponential.
4.2. With 8 products, : , so , no better than the classic algorithm. With 7 products, : . For , the classic method performs multiplications, and Strassen's , about 3.8 times fewer. In practice, the recursion stops at blocks of a few dozen elements, because the extra additions make Strassen slower for small matrices. As with Karatsuba, the improvement comes only from reducing .
4.3. Count the inversions of each half recursively, and count the "crossing" inversions (one element in each half) during the merge. When an element of the right half is copied to the output before the remaining elements of the left half, it is smaller than all of them: it forms an inversion with each one.
static long countInversions(int[] a, int[] aux, int left, int right) {
if (left >= right) return 0;
int center = left + (right - left) / 2;
long count = countInversions(a, aux, left, center)
+ countInversions(a, aux, center + 1, right);
for (int i = left; i <= right; i++) aux[i] = a[i];
int i = left, j = center + 1, k = left;
while (i <= center && j <= right) {
if (aux[i] <= aux[j]) a[k++] = aux[i++];
else {
a[k++] = aux[j++];
count += center - i + 1; // aux[j] is smaller than aux[i..center]
}
}
while (i <= center) a[k++] = aux[i++];
while (j <= right) a[k++] = aux[j++];
return count;
}
The recurrence is that of Mergesort, : . For 4 7 1 6 2 it returns 6. We checked it against brute force on 20,000 random arrays. (It sorts the array as a side effect; pass a copy if the original must be kept.)
4.4. Look at the middle element and its right neighbor. If a[mid] < a[mid + 1], the sequence rises to the right, so there is a peak to the right of mid (either the values keep rising until the end, which is a peak, or they fall somewhere, and that point is a peak). Otherwise, there is a peak at mid or to its left.
static int peak(int[] a) {
int left = 0, right = a.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (a[mid] < a[mid + 1]) left = mid + 1;
else right = mid;
}
return left;
}
Half of the range is discarded at each step: . Like binary search, but the array does not need to be sorted.
4.5. Compare the middle element with the last one. If a[mid] > a[right], the rotation point (the minimum) is to the right of mid; otherwise it is at mid or to its left.
static int minRotated(int[] a) {
int left = 0, right = a.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (a[mid] > a[right]) left = mid + 1;
else right = mid;
}
return a[left];
}
. With repeated elements it can fail: if a[mid] == a[right] (as in 2 2 2 0 2), there is no way to know on which side the minimum is. Discarding only the last element (right--) keeps it correct, but in the worst case (almost all elements equal) the cost becomes .
4.6. Binary search over the possible answers: the largest with .
static long isqrt(long n) {
long left = 0, right = Math.min(n, 3_037_000_499L); // the square of the bound fits in a long
while (left <= right) {
long mid = left + (right - left) / 2;
if (mid * mid <= n) left = mid + 1;
else right = mid - 1;
}
return right;
}
iterations. For the range has about candidates, so about 32 iterations (31 in our run), and the result is . The upper bound avoids overflow when computing mid * mid. (Using Math.sqrt on a double can be wrong by one for large long values, because a double has only 53 bits of precision.)
4.7. Split the coins into three groups as equal as possible and weigh two of them against each other. If one pan is lighter, the counterfeit is in that group; if they balance, it is in the third group. Each weighing keeps one third of the coins: , so weighings. For 27 coins, 3 weighings (). For 1,000 coins, 7 (). Splitting into two halves would need weighings (5 and 10): a balance has three outcomes, and dividing by 3 uses all of them.
4.8. Choose how many elements of a belong to the lower half of the union (the smallest elements); then come from b. The choice is correct when a[i-1] <= b[j] and b[j-1] <= a[i], and the median is then the larger of a[i-1] and b[j-1]. If a[i-1] > b[j], too many elements were taken from a, so must decrease; otherwise it must increase. Binary search on between 0 and :
static int median(int[] a, int[] b) {
int n = a.length, lo = 0, hi = n;
while (true) {
int i = (lo + hi) / 2, j = n - i;
int aLeft = (i == 0) ? Integer.MIN_VALUE : a[i - 1];
int aRight = (i == n) ? Integer.MAX_VALUE : a[i];
int bLeft = (j == 0) ? Integer.MIN_VALUE : b[j - 1];
int bRight = (j == n) ? Integer.MAX_VALUE : b[j];
if (aLeft <= bRight && bLeft <= aRight) return Math.max(aLeft, bLeft);
if (aLeft > bRight) hi = i - 1;
else lo = i + 1;
}
}
Each step halves the range of : . We compared it with merging and sorting on 20,000 random pairs of arrays. Merging would cost .
Errors, suggestions and public questions open a form on GitHub, visible to everyone.