Data structures and algorithms

Exercise solutions: Complexity, parts B–C

Here are suggested solutions to the exercises about complexity, parts B and C.

Core exercises (part B)

B1. Simplify orders of growth

B2. Deletion from a dynamic array

(We assume that the dynamic array does not resize automatically after deletion, which is in fact how ArrayList behaves in Java.)

B3. Give proofs of the following rules for O-notation

All cases have the same hypotheses. These give us:

Then we have:

B4. Asymptotic complexities of recursive functions

Bonus exercises (part C)

C1. Accidentally Quadratic

There’s no answer since this wasn’t really a question…

C2. Problems from S&W chapter 1.4

Some of the problems have answers or hints on the website, otherwise you’re on your own :).

C3. Prove or disprove

C4. Preorder

Reflexivity (f(n) ∈ O(n)) holds trivially: we have f(n) ≤ 1 ∙ f(n) for n ≥ 1. For transitivity, if f(n) is bounded by C g(n) for n ≥ n₀ and g(n) is bounded by D h(n) for n ≥ n₁, then f(n) is bounded by CD h(n) for n ≥ max(n₀, n₁). Thus, the relation defined by O forms a preorder (called the order-of-growth order).

If O(f(n)) ⊆ O(g(n)), then f(n) ∈ O(g(n)) follows from reflexivity (f(n) ∈ O(n)). Conversely, if f(n) ∈ O(g(n)), then O(f(n)) ⊆ O(g(n)) follows using transitivity established above.

Let us construct f, g : ℕ → ℝ>0 such that neither f(n) ∈ O(g(n)) nor g(n) ∈ O(f(n)). There are many possible ideas, one is the following:

The ratio f(n) / g(n) grows arbitrarily large. Thus, there cannot be C and n₀ such that f(n) / g(n) ≤ C for n ≥ n₀. This shows that f(n) ∈ O(g(n)) does not hold. An analogous argument shows that g(n) ∈ O(f(n)) does not hold.

From this example, we can build another one whose functions are increasing. The idea is to multiply f and g by the same fast-growing function h, i.e. set f’(n) = h(n) f(n) and g’(n) = h(n) g(n). Then the ratios of f’ and g’ are identical to those of f and g, so neither f’(n) ∈ O(g’(n)) nor g’(n) ∈ O(f’(n)) hold. Picking the factorial function h(n) = n! makes f’ and g’ increasing.

C5. Polynomial order of growth

Assume f(2n) ∈ O(f(n)). That means there are C and n0 such that f(2n) ≤ C f(n) for n ≥ n0. By induction on m, we get that f(2m) ≤ Cm f(1). Since f is increasing, we have

So f ∈ O(nk) for k = log2(C).