DSC 40B

Problems tagged with "lecture-06"

Problem #127

Tags: best and worst case, lecture-06, mergesort

True or False: the best case time complexity of mergesort is \(\Theta(n)\).

Solution

False.

Mergesort doesn't stop early: it always splits the array in half all the way down and merges everything back together, no matter what the input is (even if it is already sorted). Each of the \(\Theta(\log n)\) levels of recursion does \(\Theta(n)\) merging work, so the best case is \(\Theta(n \log n)\), the same as the worst case.

Problem #129 🌶️

Tags: lecture-06, mergesort

Suppose mergesort is called on an array of size \(n\). In total, how many calls to merge are made over all calls to mergesort?

Solution

\(\Theta(n)\).

Each call to mergesort on an array of size 2 or more splits it in two, makes two recursive calls, and then calls merge exactly once. Calls on arrays of size 1 (or 0) are base cases: they don't recurse and don't merge. So the number of calls to merge is the number of non-base-case calls, i.e., the number of internal nodes of the recursion tree.

The recursion tree has one leaf for each element of the array, so it has \(n\) leaves. Every internal node has exactly two children, and a tree like that with \(n\) leaves has \(n - 1\) internal nodes. (Each merge combines two sorted pieces into one, starting from \(n\) pieces of size 1 and ending with one piece, so it takes \(n - 1\) merges.) For example, when \(n = 8\) there are \(4 + 2 + 1 = 7\) merges. So the total is \(n - 1 = \Theta(n)\).

Problem #130

Tags: lecture-06, recurrence relations

What is the solution of the below recurrence? State your answer using asymptotic notation as a function of \(n\).

\[ T(n) = \begin{cases} 5 T(n/5) + \Theta(n),& n > 1\\ 1,& n = 1 \end{cases} \]
Solution

\(\Theta(n \log n)\).

At depth \(k\) of the recursion tree there are \(5^k\) subproblems of size \(n/5^k\), so each level does \(5^k \cdot \Theta(n / 5^k) = \Theta(n)\) work. There are \(\log_5 n\) levels, so the total is \(\Theta(n \log n)\).

Problem #131

Tags: lecture-06, recurrence relations

State (but do not solve) the recurrence describing the runtime of the following function.

def foo(n):
    if n <= 1:
        return

    foo(n // 2)

    for j in range(n):
        print(j)

    foo(n // 2)
Solution

\( T(n) = \begin{cases} \Theta(1), & n = 1\\ 2 T(n/2) + \Theta(n), & n > 1 \end{cases} \)

There are two recursive calls, each on an input of size \(n/2\), and the loop between them does \(\Theta(n)\) work.

Problem #132

Tags: lecture-06, recurrence relations

State (but do not solve) the recurrence describing the runtime of the following function.

def foo(n):
    if n < 10:
        print("Hello world.")
        return

    for i in range(n):
        print(i)

    for i in range(6):
        foo(n//3)
Solution

\(T(n) = 6 T(n/3) + \Theta(n)\).

The first loop does \(\Theta(n)\) work, and the second loop makes 6 recursive calls, each on an input of size \(n // 3 \approx n/3\).

Problem #133

Tags: lecture-06, recurrence relations

State (but do not solve) the recurrence describing the runtime of the following function.

def boo(n):
    if n <= 1:
        return

    for i in range(3):
        boo(n // 4)

    for j in range(n):
        print(j)
Solution

\(T(n) = 3 T(n/4) + \Theta(n)\).

Even though the recursive calls are made in a for-loop, the basic idea is the same: there will be three recursive calls, each on an input of size \(n/4\), and thus the recurrence will involve \(3 T(n/4)\). There is \(\Theta(n)\) work done outside the recursive calls, for a full recurrence of \(T(n) = 3 T(n/4) + \Theta(n)\).

Problem #134

Tags: lecture-06, recurrence relations

State (but do not solve) the recurrence relation describing this function's run time.

import random

def foo(n):
    if n <= 2:
        return 1

    for i in range(n):
        for j in range(i, n):
            print(i)

    return foo(n//2) + foo(n//2)
Solution

\(T(n) = 2 T(n/2) + \Theta(n^2)\).

The nested loops are dependent: the inner loop runs \(n - i\) times, for a total of \(n + (n-1) + \ldots + 1 = \Theta(n^2)\). Then there are two recursive calls, each on a problem of size \(n/2\).

Problem #135 🌶️

Tags: lecture-06, mergesort, recursion

Consider the code for mergesort and merge where a new print-statement has been added to merge:

def mergesort(arr):
    """Sort array in-place."""
    if len(arr) > 1:
        middle = math.floor(len(arr) / 2)
        left = arr[:middle]
        right = arr[middle:]
        mergesort(left)
        mergesort(right)
        merge(left, right, arr)

def merge(left, right, out):
    """Merge sorted arrays, store in out."""
    left.append(float('inf'))
    right.append(float('inf'))
    left_ix = 0
    right_ix = 0

    for ix in range(len(out)):
        print("Here!") # <---- the newly-added line
        if left[left_ix] < right[right_ix]:
            out[ix] = left[left_ix]
            left_ix += 1
        else:
            out[ix] = right[right_ix]
            right_ix += 1

Suppose mergesort is called on an array of size \(n\). In total, how many times will "Here!" be printed?

Solution

\(\Theta(n \log n)\).

The print is inside merge's loop, which runs once for each element of out. So a call to merge that produces an array of size \(m\) prints “Here!” \(m\) times, i.e., the number of prints is exactly the number of elements merged.

Now look at the recursion tree of mergesort. At each level, the subarrays being sorted together make up the whole array (each element is in exactly one of them), so the merges at that level produce at most \(n\) elements in total, and exactly \(n\) at every level above the leaves. There are \(\Theta(\log n)\) levels, since the size halves at each one. So the total number of prints is \(\Theta(n)\) per level times \(\Theta(\log n)\) levels, which is \(\Theta(n \log n)\). This is the same argument that shows mergesort takes \(\Theta(n \log n)\) time.

Problem #136

Tags: lecture-06, time complexity

import math

def mediansort(arr, start, stop):
    """Claims to sort the array, in-place"""
    if stop - start <= 1:
        return

    # finds the index of the median of arr[start:stop]
    median_ix = find_median(arr, start, stop)

    middle_ix = math.floor((start + stop) / 2)

    # move the median to the middle by swapping
    arr[median_ix], arr[middle_ix] = arr[middle_ix], arr[median_ix]

    # recurse on the left and right halves
    mediansort(arr, start, middle_ix)
    mediansort(arr, middle_ix + 1, stop)

Consider the mediansort function from above. Suppose that find_median takes \(\Theta(n)\) time. What is the time complexity of mediansort?

Solution

\(\Theta(n \log n)\).

Each call does \(\Theta(n)\) work (find_median plus a constant-time swap) and recurses on two halves of size about \(n/2\), so \(T(n) = 2T(n/2) + \Theta(n)\), the same recurrence as mergesort, whose solution is \(\Theta(n \log n)\).

Problem #137

Tags: lecture-06, mergesort, recurrence relations

Consider the modification of mergesort shown below, where one of the recursive calls has been replaced by an in-place version of selection_sort. Recall that selection_sort takes \(\Theta(n^2)\) time.

def kinda_mergesort(arr):
    """Sort array in-place."""
    if len(arr) > 1:
        middle = math.floor(len(arr) / 2)
        left = arr[:middle]
        right = arr[middle:]
        mergesort(left)
        selection_sort(right)
        merge(left, right, arr)

What is the time complexity of kinda_mergesort?

Solution

\(\Theta(n^2)\).

The function isn't actually recursive: it calls the regular mergesort on the left half, taking \(\Theta(n \log n)\) time, selection_sort on the right half, taking \(\Theta((n/2)^2) = \Theta(n^2)\) time, and merge, taking \(\Theta(n)\) time. The selection sort dominates, so the total is \(\Theta(n^2)\).

Problem #138

Tags: best and worst case, lecture-06, mergesort

Suppose arr is a list-of-lists with \(n\) inner lists, each containing \(n\) numbers. What is the best case time complexity of the following function?

import math

def average_median(arr):
    """Compute the mean of the row medians."""
    msum = 0
    for row in arr:
        mergesort(row) # sort the row using the mergesort algorithm
        msum += row[math.floor(len(row) / 2)]
    return msum / len(arr)
Solution

\(\Theta(n^2 \log n)\).

Mergesort takes \(\Theta(k \log k)\) time on an array of size \(k\) in every case, including the best case. The loop sorts \(n\) rows of size \(n\), taking \(\Theta(n \log n)\) time for each, and the rest of the loop body takes constant time. So the best case is \(\Theta(n^2 \log n)\).

Problem #139

Tags: best and worst case, lecture-06, mergesort

Your friend has written a modified version of mergesort that they claim has an improved best-case time complexity:

def better_mergesort(arr):
    if is_already_sorted(arr):
        return
    else:
        mergesort(arr)

Here, is_already_sorted is a function that takes in an array and returns True if and only if the array is in sorted order. Assume that is_already_sorted is implemented efficiently (meaning, it has the best possible time complexity). What is the best case time complexity of better_mergesort?

Solution

\(\Theta(n)\).

The best case is when arr is already sorted, so that only is_already_sorted runs. Checking whether an array is sorted requires looking at every element, and can be done in \(\Theta(n)\) time by comparing each pair of adjacent elements. So the best case time complexity is \(\Theta(n)\).

Problem #140

Tags: binary search, lecture-06, loop invariants

Consider the iterative implementation of binary search shown below:

import math

def iterative_binary_search(arr, target):

    start = 0
    stop = len(arr)

    while (stop - start) > 0:
        print(arr[start])
        middle = math.floor((start + stop) / 2)
        if arr[middle] == target:
            return middle
        elif arr[middle] > target:
            stop = middle
        else:
            start = middle + 1

    return None

Which of the following loop invariants are true, assuming that arr is sorted and non-empty, and target is not in the array? Select all that apply.

Solution

Only stop - start >= 0 is a loop invariant.

It holds initially, and middle is always between start and stop - 1, so setting stop = middle or start = middle + 1 never makes start pass stop. The second option fails after the last iteration: the loop only ends (with the target not in the array) when stop - start is 0. The third fails if the target is smaller than every element: start stays 0, and arr[0] is greater than the target.

Problem #141

Tags: lecture-06, loop invariants, selection sort

Suppose you are sorting an array using selection sort. At the current iteration of selection sort, the array being sorted looks like this:

[0, 1, 2, 2, 3, 4, 2, 10, 13, 4]

Which of the following are possible options for how many times the outer for loop has run? Select all that apply.

Solution

1, 2, 3, and 4.

Remember the selection sort loop invariants: after the \(\alpha\)th iteration, the first \(\alpha\) numbers are \(\leq\) the remaining numbers, and the first \(\alpha\) numbers are in sorted order.

To answer this question, we can ask, for each \(\alpha\), are the loop invariants true? If yes, then it is possible that \(\alpha\) iterations have been made; if not, then it is not possible.

It is true for \(\alpha=1\), since the first number is \(\leq\) the remaining numbers, and the first 1 numbers are in sorted order. Same for \(\alpha = 2, 3, \) and \(4\). However, it is not true at \(\alpha = 5\). One of the loop invariants is true (the first five numbers are in sorted order), but the other is not: the first 5 numbers are not all \(\leq\) the remaining numbers. In particular, the fifth number (3) is not \(\leq\) the 7th number (2). Therefore, this could not possibly be the result after 5 iterations.

Problem #142 🌶️

Tags: lecture-06, mergesort

Below is the merge function from the mergesort algorithm, with an added print statement:

def merge(left, right, out):
    """Merge sorted arrays, store in out."""
    print(len(left))
    print(len(right))
    left.append(float('inf'))
    right.append(float('inf'))
    left_ix = 0
    right_ix = 0

    for ix in range(len(out)):
        if left[left_ix] < right[right_ix]:
            out[ix] = left[left_ix]
            left_ix += 1
        else:
            out[ix] = right[right_ix]
            right_ix += 1

Suppose this version of merge is used in mergesort, and mergesort is called on the following list:

[6, 2, 7, 1, 9, 3, 8, 5]

If all of the numbers that are printed are added up, what will the sum be?

Solution

24.

Each call to merge prints the sizes of its two halves, which add up to the size of the subarray being merged. So we need the total size of all the subarrays that get merged. Since the list has 8 elements, the recursion splits it in halves evenly:

\[ \begin{aligned} \text{merging size-8 arrays:}&\quad 4 + 4 = 8 \\ \text{merging size-4 arrays (2 of them):}&\quad 2 \cdot (2 + 2) = 8 \\ \text{merging size-2 arrays (4 of them):}&\quad 4 \cdot (1 + 1) = 8 \end{aligned} \]

Arrays of size 1 are base cases and aren't merged. Each level's printed sizes add up to 8, the size of the whole list, and there are \(\log_2 8 = 3\) levels of merges, so the sum is \(3 \cdot 8 = 24\). Notice that the values in the list don't matter, only its length.

Problem #145 🌶️

Tags: lecture-06, theoretical lower bounds

Consider the problem of determining whether there exists a pair of numbers in an array which, when added together, equal the maximum number in the array. Additionally, assume that the array is sorted.

True or False: \(\Theta(n)\) is a tight theoretical lower bound for this problem.

Solution

True.

Any algorithm must take \(\Omega(n)\) time in the worst case, since in the worst case all elements of the array must be read.

This is tight because there is an algorithm that will compute the answer in worst-case \(\Theta(n)\) time. Namely, this is an instance of the “movie problem” from lecture, where instead of finding two numbers which add to an arbitrary target, we're looking for a specific target: the maximum. We saw an algorithm that solved the movie problem in \(\Theta(n)\) time, where \(n\) was the number of movies. Since the maximum is computed in \(\Theta(1)\) time for a sorted array, we can use the same algorithm to solve this in \(\Theta(n)\) time as well.

Problem #146 🌶️

Tags: lecture-06, theoretical lower bounds

In this problem, assume that \(A\) and \(B\) are sorted lists, each containing \(n\) numbers.

Part 1)

What is the best possible (worst case) time complexity of any algorithm for finding the smallest difference between a number in \(A\) and a number in \(B\)?

Solution

\(\Theta(n)\).

We can do it in \(\Theta(n)\) time with a two-pointer scan like merge: start with \(i = j = 0\), record \(|A[i] - B[j]|\), and advance whichever pointer points to the smaller number. The closest pair is always checked, because we only move past a number once every number it could be closer to has been passed.

We can't do better, because any algorithm must read every element in the worst case. For example, if \(A = 1, 3, 5, \ldots\) and \(B = 2, 4, 6, \ldots\), the smallest difference is 1. If an algorithm never reads some element of \(A\), say \(A[i] = 2i + 1\), then that element could instead have been \(2i + 2\), which keeps \(A\) sorted and equals \(B[i]\), making the smallest difference 0. The algorithm sees the same thing either way, so it is wrong on one of the two inputs.

Part 2)

What is the best possible (worst case) time complexity of any algorithm for finding the biggest difference between a number in \(A\) and a number in \(B\)?

Solution

\(\Theta(1)\).

The biggest difference is between the largest number in one list and the smallest number in the other. Since both lists are sorted, these are at the ends of the lists, so the answer is \(\max(|A[n-1] - B[0]|, |B[n-1] - A[0]|)\). Computing this reads four elements, no matter how big \(n\) is, so it takes \(\Theta(1)\) time.

Problem #147 🌶️

Tags: best and worst case, lecture-06, theoretical lower bounds

Consider the following problem: given two sorted lists, A and B, each containing \(n\) numbers, determine if the two lists share an element in common. That is, determine if there is a number \(x\) which appears in both lists.

Part 1)

What is a tight theoretical lower bound for this problem? Again, you may assume that the lists are both sorted. State your answer in asymptotic notation as a function of \(n\).

Solution

\(\Theta(n)\).

The two-pointer algorithm in the next part solves the problem in \(\Theta(n)\) time, so the lower bound is at most that. To see that no algorithm can do better, consider \(A = 1, 3, 5, \ldots, 2n - 1\) and \(B = 2, 4, 6, \ldots, 2n\), which share no elements. Suppose an algorithm answers “no” without reading some element, say \(A[i] = 2i + 1\). That element could instead have been \(2i + 2\): \(A\) is still sorted, and now \(A[i] = B[i]\), so the right answer is “yes.” The algorithm sees the same thing on both inputs, so it is wrong on one of them. So any correct algorithm must read all \(2n\) elements in the worst case, and the lower bound is \(\Omega(n)\).

Part 2)

Briefly (in 50 words or less) describe an optimal algorithm for solving this problem and state its worst case time complexity. You may write pseudocode if you like, but an explanation in words is also sufficient.

Solution

Here's an approach that takes \(\Theta(n)\); it's similar to what we did in lecture for the movie problem.

Start with i = j = 0. If A[i] == B[j], return True, since you've found an element in common. If A[i] > B[j], increment j, otherwise increment i. Takes \(\Theta(n)\) time.

A brute force approach, which is correct but not optimal, loops over all pairs, checking if A[i] == B[j] for each pair. This takes \(\Theta(n^2)\) time.

Problem #153

Tags: lecture-06, recurrence relations

Solve the below recurrence, stating the solution in asymptotic notation. Show your work.

\[ T(n) = \begin{cases} 2 T(n/4) + \Theta(n) & n > 1 \\ c & n = 1 \end{cases} \]
Solution

\(\Theta(n)\).

We'll unroll several times:

\[ \begin{aligned} T(n) &= 2 T(n/4) + n \\ &= 4 T(n/16) + \frac{n}{2} + n \\ &= 8 T(n/64) + \frac{n}{4} + \frac{n}{2} + n \\ \end{aligned} \]

The pattern seems to be that on the \(k\)th unroll:

\[ T(n) = 2^k T\left(\frac{n}{4^k} \right)+ n \left( 1 + \frac12 + \frac14 + \ldots + \frac{1}{2^{k-1}} \right) \]

The base case is reached when \(k = \log_4 n\). Plugging this back in, we find:

\[ T(n) = 2^{\log_4 n} T(1) + n \left(1 + \frac12 + \frac 14 + \ldots + \frac{1}{2^{\log_4 n - 1}}\right) \]

If you're unsure of what to do with \(2^{\log_4 n}\), there are a couple of ways forward.

The first (and easiest) way is to realize that \(2^{\log_4 n}\) is smaller than \(2^{\log_2 n} = n\), so \(2^{\log_4 n} = O(n)\). Similarly, we've seen the summation of \(1 + 1/2 + 1/4 + \ldots\) several times—this is a geometric sum, and converges to 2 when there are infinitely many terms. There are a finite number of terms here, so the sum is \(< 2\). Altogether, we have:

\[ T(n) = O(n) T(1) + n \Theta(1) = \Theta(n) \]

The second approach is to remember log properties to simplify \(2^{\log_4 n}\) to \(\sqrt{n}\). This can be seen by using the “change of base” formula:

\[ \log_b x = \frac{\log_a x}{\log_a b}. \]

In this case:

\[ \log_4 n = \frac{\log_2 n}{\log_2 4} = \frac{\log_2 n}{2} \]

And therefore \(2^{\log_4 n} = 2^{(\log_2 n) / 2} = \left(2^{\log_2 n}\right)^{1/2} = n^{1/2} = \sqrt n\). This shows that the first term in the recurrence is \(\Theta(\sqrt n)\). The second term is still \(\Theta(n)\), so the solution is \(\Theta(n)\).

Problem #159

Tags: lecture-06, recurrence relations

What is the time complexity of this function? Here \(n\) is the length of the input array.

import math
def foo(arr):
    if len(arr) == 0:
        return 0

    if len(arr) == 1:
        return arr[0]

    if len(arr) == 2:
        return arr[0] + arr[1]

    one_third = math.floor(len(arr) / 3)
    left = arr[:one_third]
    middle = arr[one_third: one_third * 2]
    right = arr[one_third * 2:]

    for i in range(len(arr)):
        if i < one_third:
            arr[i] = 2 * arr[i] - sum(left)/len(left)
        if i >= one_third and i < one_third * 2:
            arr[i] = 2 * arr[i] - sum(middle)/len(middle)
        if i >= one_third * 2:
            arr[i] = 2 * arr[i] - sum(right)/len(right)

    total = sum(left) + sum(middle) + sum(right)

    return foo(left) + foo(middle) + foo(right) + total
Solution

\(\Theta(n^2)\).

This does \(\Theta(n^2)\) work outside of the recursive calls. The recurrence relation is \(T(n) = 3T(n/3) + \Theta(n^2)\), whose solution is \(\Theta(n^2)\).

Solving this recurrence involves a little bit more than usual, because you have to recognize a geometric sum. When unrolling, you should find that on step \(k\) you get a term of the form \(n^2 + n^2/3 + n^2/3^2 + n^2/3^3 + ... + n^2/3^{k-1}\). This is a geometric sum, which we saw in an earlier homework. If you factor out the \(n^2\), you get something of the form \(1 + 1/3 + 1/3^2 + ...\). There is an exact formula for this, but for our purposes all that matters is that the sum converges to some number (a constant), and so the recurrence is \(\Theta(n^2)\).