Skip to main content

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 n=6n = 6 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.)

Solution to 1.1

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.

Solution to 1.2

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.

Solution to 1.3

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.

Solution to 1.4

1.5. Emptying a list. An ArrayList contains nn 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?

Solution to 1.5

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?

Solution to 1.6

1.7. Infer the complexity. A program, run without optimization (-Xint), gives these times:

nn1,0002,0004,0008,000
Time (ms)1204801,9107,700

What complexity do the measurements suggest? Predict the time for n=32,000n = 32{,}000.

Solution to 1.7

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.

Solution to 1.8

1.9. Average case with failures. A sequential search looks for a value in an array of nn elements. With probability pp the value is present, equally likely in any position; with probability 1−p1 - p it is absent. How many elements does the search examine on average? Check your formula for p=1p = 1 and p=0p = 0.

Solution to 1.9

Asymptotic notation and growth​

1.10. True or false? Justify each answer.

  • (a) 2n+1∈O(2n)2^{n+1} \in O(2^n)
  • (b) 22n∈O(2n)2^{2n} \in O(2^n)
  • (c) log⁡2(n!)∈Θ(nlog⁡n)\log_2 (n!) \in \Theta(n \log n)
  • (d) n1.01∈O(nlog⁡2n)n^{1.01} \in O(n \log^2 n)
  • (e) max⁡(f(n),g(n))∈Θ(f(n)+g(n))\max(f(n), g(n)) \in \Theta(f(n) + g(n)), for positive functions ff and gg

Solution to 1.10

1.11. Order by growth. Order from slowest to fastest growth (logarithms in base 2): nn, n\sqrt{n}, nlog⁡23n^{\log_2 3}, log⁡2n\log^2 n, 2n2^n, nlog⁡nn \log n, n/log⁡nn / \log n, 1.1n1.1^n, n1/3n^{1/3}, n2n^2.

Solution to 1.11

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 nn? What is its complexity?

Solution to 1.12

1.13. Doubling bounds. What is the complexity of this fragment? Be careful: it is not O(nlog⁡n)O(n \log n).

for (int i = 1; i < n; i *= 2)
for (int j = 0; j < i; j++)
operation(); // O(1)

Solution to 1.13

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)
}

Solution to 1.14

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 (log⁡3n\log_3 n instead of log⁡2n\log_2 n). Is it faster? Count comparisons, not iterations.

Solution to 1.15

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 ii can be read. Design an algorithm that finds a value xx located at position pp in O(log⁡p)O(\log p) time.

Solution to 1.16


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 n≥1n \ge 1. This is the famous Collatz conjecture, open since 1937: it has been verified by computer for every nn up to 271≈2.4×10212^{71} \approx 2.4 \times 10^{21} (D. Barina, 2025), but not proved. So the method is a correct algorithm only if the conjecture is true.

Back to exercise 1.1

1.2. One possible specification:

  • Precondition: a is not null and a.length >= 1. (Alternative: allow the empty array and return −1-1 for it. Either is acceptable, but the specification must say which.)
  • Postcondition: returns an index kk with 0≤k<0 \le k \lt a.length such that a[k] <= a[i] for every ii, and a[k] < a[i] for every i<ki \lt k; 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.

Back to exercise 1.2

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 9⋅9=819 \cdot 9 = 81 instead of 3636. 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.

Back to exercise 1.3

1.4.

  • (a) A stack (ArrayDeque used with push/pop): O(1)O(1) per operation.
  • (b) A queue (ArrayDeque used with offer/poll): O(1)O(1).
  • (c) A HashSet: add and contains in O(1)O(1) on average. A list would need O(n)O(n) per check.
  • (d) A TreeMap<String, Integer>: each update is O(log⁡n)O(\log n), and iterating over it gives the words in alphabetical order. (A HashMap followed by sorting the keys at the end is also valid.)
  • (e) A PriorityQueue: insertion and extraction of the maximum (with a suitable comparator) in O(log⁡n)O(\log n).

Back to exercise 1.4

1.5. With remove(0), each call shifts all the remaining elements one position to the left: (n−1)+(n−2)+⋯+0=n(n−1)2(n-1) + (n-2) + \dots + 0 = \frac{n(n-1)}{2} moves, O(n2)O(n^2). With remove(size() - 1) nothing is shifted: O(1)O(1) per call, O(n)O(n) in total. An ArrayList is an array; only its end is cheap to modify. (An ArrayDeque would allow removing from either end in O(1)O(1).)

Back to exercise 1.5

1.6. For 50 ms you need 50,000/2=25,00050{,}000 / 2 = 25{,}000 executions, so 10510^5 repetitions (about 200 ms). The time of one execution is the total divided by 10510^5, expressed in microseconds. With fewer repetitions the measurement is dominated by the 1 ms resolution of the clock.

Back to exercise 1.6

1.7. Each time nn doubles, the time multiplies by about 4 (480/120=4.0480/120 = 4.0; 1910/480≈3.981910/480 \approx 3.98; 7700/1910≈4.037700/1910 \approx 4.03): the algorithm is O(n2)O(n^2). From n=8,000n = 8{,}000 to 32,00032{,}000 the size multiplies by 4, so the time multiplies by about 42=164^2 = 16: 7.7⋅16≈1237.7 \cdot 16 \approx 123 seconds, about 2 minutes.

Back to exercise 1.7

1.8. The size of the input is nn = a.length.

  • Best case: the first two elements are equal. One comparison: O(1)O(1).
  • Worst case: no two consecutive elements are equal (or only the last two are). The loop makes n−1n - 1 comparisons: O(n)O(n). For an empty or one-element array, the loop does not run: zero comparisons.

Back to exercise 1.8

1.9. If the value is present at position ii (counting from 1), the search examines ii elements; averaged over the nn positions, n+12\frac{n+1}{2}. If it is absent, it examines all nn. So the average is

p⋅n+12+(1−p)⋅np \cdot \frac{n+1}{2} + (1 - p) \cdot n

For p=1p = 1 it gives n+12\frac{n+1}{2} (the classic average); for p=0p = 0, nn (always the worst case). For n=100n = 100 and p=0.6p = 0.6 it gives 70.3, and a simulation with 200,000 random searches gave 70.31.

Back to exercise 1.9

1.10.

  • (a) True: 2n+1=2⋅2n2^{n+1} = 2 \cdot 2^n, a constant times 2n2^n.
  • (b) False: 22n=4n2^{2n} = 4^n, and 4n/2n=2n4^n / 2^n = 2^n is not bounded by any constant.
  • (c) True: log⁡2(n!)=log⁡21+⋯+log⁡2n≤nlog⁡2n\log_2 (n!) = \log_2 1 + \dots + \log_2 n \le n \log_2 n, and the largest n/2n/2 terms are each at least log⁡2(n/2)\log_2 (n/2), so it is also at least n2log⁡2n2\frac{n}{2} \log_2 \frac{n}{2}. See Sums, Logarithms and Factorials.
  • (d) False: dividing both by nn, it would require n0.01∈O(log⁡2n)n^{0.01} \in O(\log^2 n), but every positive power of nn eventually exceeds every power of log⁡n\log n. (For this pair, "eventually" means astronomically large nn, which shows that asymptotic statements can be true but irrelevant in practice.)
  • (e) True: max⁡(f,g)≤f+g≤2max⁡(f,g)\max(f, g) \le f + g \le 2 \max(f, g).

Back to exercise 1.10

1.11. log⁡2n\log^2 n, n1/3n^{1/3}, n\sqrt{n}, n/log⁡nn / \log n, nn, nlog⁡nn \log n, nlog⁡23≈n1.585n^{\log_2 3} \approx n^{1.585}, n2n^2, 1.1n1.1^n, 2n2^n. Every exponential, even with base 1.1, eventually exceeds every polynomial.

Back to exercise 1.11

1.12. After kk iterations, s=2+3+⋯+(k+1)=(k+1)(k+2)2−1≈k22s = 2 + 3 + \dots + (k+1) = \frac{(k+1)(k+2)}{2} - 1 \approx \frac{k^2}{2}. The loop stops when s≥ns \ge n, that is, when k≈2nk \approx \sqrt{2n}. Its complexity is O(n)O(\sqrt{n}). Counting the iterations: 13 for n=100n = 100, 140 for n=104n = 10^4 and 1,413 for n=106n = 10^6, against 2n=14.1\sqrt{2n} = 14.1, 141.4 and 1414.2.

Back to exercise 1.12

1.13. The inner loop runs ii times, and ii takes the values 1,2,4,…1, 2, 4, \dots up to less than nn. The total is a geometric series dominated by its last term: 1+2+4+⋯+2k<2⋅2k<2n1 + 2 + 4 + \dots + 2^k \lt 2 \cdot 2^k \lt 2n. The fragment is O(n)O(n). Multiplying "the outer loop runs log⁡n\log n times" by "the inner loop runs at most nn times" gives a correct but loose upper bound, O(nlog⁡n)O(n \log n).

Back to exercise 1.13

1.14. The outer loop always runs nn times, and for each ii the inner loop stops at the first negative element from position ii on. Best case: every element is negative, so each inner loop stops at its first step: O(n)O(n). Worst case: no element is negative, so the inner loop runs n−in - i times for each ii, in total n(n+1)2\frac{n(n+1)}{2}: O(n2)O(n^2). (A single negative element at position 0 is not the best case: it only stops the first inner loop.)

Back to exercise 1.14

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 4log⁡3n≈2.52log⁡2n4 \log_3 n \approx 2.52 \log_2 n comparisons against 2log⁡2n2 \log_2 n. For an array of 10610^6 elements, searching for a value larger than all of them, we counted 40 comparisons for binary search and 52 for ternary search. Both are O(log⁡n)O(\log n), but splitting in two is better. (With a single "less than" comparison per probe, the same argument holds: 2log⁡3n≈1.26log⁡2n2 \log_3 n \approx 1.26 \log_2 n against log⁡2n\log_2 n.)

Back to exercise 1.15

1.16. Exponential (or galloping) search. First read positions 1,2,4,8,…1, 2, 4, 8, \dots until finding a position 2k2^k whose element is greater than or equal to xx (or that does not exist). This takes about log⁡2p+1\log_2 p + 1 reads, since 2k−1<p≤2k2^{k-1} \lt p \le 2^k. Then run binary search between positions 2k−12^{k-1} and 2k2^k, a range of fewer than pp elements: another O(log⁡p)O(\log p) steps. In total, O(log⁡p)O(\log p), which is much better than O(log⁡N)O(\log N) 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.

Back to exercise 1.16

Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.