Exercises: Principles of Algorithmics
These exercises review the whole chapter, from the definition of an algorithm to searching. They are ordered by lesson, and within each group from easier to harder. Try each one before reading its solution: the solutions are grouped at the end of the page.
Algorithms and specifications
1.1. Is it an algorithm? Consider this method:
static int steps(int n) { // n >= 1
int count = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
count++;
}
return count;
}
For the sequence is 6, 3, 10, 5, 16, 8, 4, 2, 1. Is this method an algorithm according to the definition of the first lesson? (Ignore integer overflow.)
1.2. Specify. Write a precondition and a postcondition for a method int indexOfMin(int[] a) that returns the position of the smallest element of an array. Your specification must say what happens when the array is empty and when the minimum appears more than once.
Case study and stress testing
1.3. Find the counterexample. This method tries to compute the maximum pairwise product of an array of non-negative integers (at least two elements) in linear time:
static long maxPairwise(int[] a) {
int i1 = 0;
for (int i = 0; i < a.length; i++)
if (a[i] > a[i1]) i1 = i; // position of the largest
int i2 = 0;
for (int i = 0; i < a.length; i++)
if (i != i1 && a[i] > a[i2]) i2 = i; // position of the second largest
return (long) a[i1] * a[i2];
}
It passes many tests. Find the smallest input on which it fails, explain the bug, and fix it.
Data structures
1.4. Choose the structure. For each task, choose a Java collection and give the cost of its main operation:
- (a) The "undo" history of a text editor.
- (b) A list of print jobs, served in order of arrival.
- (c) Detecting whether a number has already appeared in a stream of millions of numbers.
- (d) Counting how many times each word appears in a text, and printing the words in alphabetical order.
- (e) Always attending first the pending task with the highest priority.
1.5. Emptying a list. An ArrayList contains elements. What is the cost of removing all of them with n calls to remove(0)? And with n calls to remove(list.size() - 1)? Why the difference?
Measuring efficiency
1.6. How many repetitions? One execution of a method takes about 2 µs, and you measure with System.currentTimeMillis(), whose resolution is about 1 ms. How many repetitions (a power of 10) do you need for the total time to exceed 50 ms? How do you obtain the time of one execution?
1.7. Infer the complexity. A program, run without optimization (-Xint), gives these times:
| 1,000 | 2,000 | 4,000 | 8,000 | |
|---|---|---|---|---|
| Time (ms) | 120 | 480 | 1,910 | 7,700 |
What complexity do the measurements suggest? Predict the time for .
Counting operations and cases
1.8. Equal neighbors. This method checks whether an array has two equal consecutive elements:
static boolean hasEqualNeighbors(int[] a) {
for (int i = 0; i + 1 < a.length; i++)
if (a[i] == a[i + 1])
return true;
return false;
}
Describe the best and the worst case, and give the number of comparisons a[i] == a[i + 1] in each.
1.9. Average case with failures. A sequential search looks for a value in an array of elements. With probability the value is present, equally likely in any position; with probability it is absent. How many elements does the search examine on average? Check your formula for and .
Asymptotic notation and growth
1.10. True or false? Justify each answer.
- (a)
- (b)
- (c)
- (d)
- (e) , for positive functions and
1.11. Order by growth. Order from slowest to fastest growth (logarithms in base 2): , , , , , , , , , .
Complexity of loops
1.12. A growing step.
int i = 1, s = 0;
while (s < n) {
i++;
s += i;
}
How many iterations does the loop perform, as a function of ? What is its complexity?
1.13. Doubling bounds. What is the complexity of this fragment? Be careful: it is not .
for (int i = 1; i < n; i *= 2)
for (int j = 0; j < i; j++)
operation(); // O(1)
1.14. Early exit. What are the best-case and worst-case complexities of this fragment, which processes each suffix of the array until it finds a negative number?
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++) {
if (a[j] < 0) break;
operation(); // O(1)
}
Searching
1.15. Ternary search. Instead of splitting the array in two, ternary search compares the target with the elements at one third and two thirds of the range, and keeps one of the three parts. It needs fewer iterations than binary search ( instead of ). Is it faster? Count comparisons, not iterations.
1.16. Searching without knowing the size. A sorted sequence is so large that its length is unknown (for example, it is generated on demand), but any position can be read. Design an algorithm that finds a value located at position in time.
Solutions
1.1. We do not know. The instructions are precise and each step is finite, but an algorithm must end for every valid input, and nobody has proved that this loop reaches 1 for every . This is the famous Collatz conjecture, open since 1937: it has been verified by computer for every up to (D. Barina, 2025), but not proved. So the method is a correct algorithm only if the conjecture is true.
1.2. One possible specification:
- Precondition:
ais notnullanda.length >= 1. (Alternative: allow the empty array and return for it. Either is acceptable, but the specification must say which.) - Postcondition: returns an index with
a.lengthsuch thata[k] <= a[i]for every , anda[k] < a[i]for every ; that is, the first position of the minimum. The array is not modified.
Without the last condition, two correct implementations could return different positions for the same input, and a test could not decide which is right.
1.3. The smallest failing input is {9, 4} (any array of size 2 whose largest element is at position 0 and is strictly larger than the other): it returns instead of . The second loop starts with i2 = 0, which is the position of the maximum itself. Since no element is larger than the maximum, i2 never changes, and the method multiplies the maximum by itself. Fix: start i2 at a position different from i1, for example int i2 = (i1 == 0) ? 1 : 0;. A stress test with random arrays of size 2 to 5 and values 0 to 9 finds this bug immediately; a test suite of "typical" arrays may never find it.
1.4.
- (a) A stack (
ArrayDequeused withpush/pop): per operation. - (b) A queue (
ArrayDequeused withoffer/poll): . - (c) A
HashSet:addandcontainsin on average. A list would need per check. - (d) A
TreeMap<String, Integer>: each update is , and iterating over it gives the words in alphabetical order. (AHashMapfollowed by sorting the keys at the end is also valid.) - (e) A
PriorityQueue: insertion and extraction of the maximum (with a suitable comparator) in .
1.5. With remove(0), each call shifts all the remaining elements one position to the left: moves, . With remove(size() - 1) nothing is shifted: per call, in total. An ArrayList is an array; only its end is cheap to modify. (An ArrayDeque would allow removing from either end in .)
1.6. For 50 ms you need executions, so repetitions (about 200 ms). The time of one execution is the total divided by , expressed in microseconds. With fewer repetitions the measurement is dominated by the 1 ms resolution of the clock.
1.7. Each time doubles, the time multiplies by about 4 (; ; ): the algorithm is . From to the size multiplies by 4, so the time multiplies by about : seconds, about 2 minutes.
1.8. The size of the input is = a.length.
- Best case: the first two elements are equal. One comparison: .
- Worst case: no two consecutive elements are equal (or only the last two are). The loop makes comparisons: . For an empty or one-element array, the loop does not run: zero comparisons.
1.9. If the value is present at position (counting from 1), the search examines elements; averaged over the positions, . If it is absent, it examines all . So the average is
For it gives (the classic average); for , (always the worst case). For and it gives 70.3, and a simulation with 200,000 random searches gave 70.31.
1.10.
- (a) True: , a constant times .
- (b) False: , and is not bounded by any constant.
- (c) True: , and the largest terms are each at least , so it is also at least . See Sums, Logarithms and Factorials.
- (d) False: dividing both by , it would require , but every positive power of eventually exceeds every power of . (For this pair, "eventually" means astronomically large , which shows that asymptotic statements can be true but irrelevant in practice.)
- (e) True: .
1.11. , , , , , , , , , . Every exponential, even with base 1.1, eventually exceeds every polynomial.
1.12. After iterations, . The loop stops when , that is, when . Its complexity is . Counting the iterations: 13 for , 140 for and 1,413 for , against , 141.4 and 1414.2.
1.13. The inner loop runs times, and takes the values up to less than . The total is a geometric series dominated by its last term: . The fragment is . Multiplying "the outer loop runs times" by "the inner loop runs at most times" gives a correct but loose upper bound, .
1.14. The outer loop always runs times, and for each the inner loop stops at the first negative element from position on. Best case: every element is negative, so each inner loop stops at its first step: . Worst case: no element is negative, so the inner loop runs times for each , in total : . (A single negative element at position 0 is not the best case: it only stops the first inner loop.)
1.15. No. Each iteration of ternary search needs up to 4 comparisons (equal to each of the two pivots, then which of the three parts), against 2 for binary search (equal to the middle, then which half). In the worst case that is about comparisons against . For an array of elements, searching for a value larger than all of them, we counted 40 comparisons for binary search and 52 for ternary search. Both are , but splitting in two is better. (With a single "less than" comparison per probe, the same argument holds: against .)
1.16. Exponential (or galloping) search. First read positions until finding a position whose element is greater than or equal to (or that does not exist). This takes about reads, since . Then run binary search between positions and , a range of fewer than elements: another steps. In total, , which is much better than when the target is near the beginning of a huge sequence. Java's TimSort (used by Arrays.sort for objects) uses this technique to merge runs efficiently.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.