Find an upper bound (Big $O$) on the worst case run time of the following code segment.
Carefully examine to see if this is a tight upper bound (Big $\Theta$)
void bigOh1(int[] L, int n)
while (n > 0)
find_max(L, n) // Finds the max in L[0..n-1]
n /= 4
Answer: The time complexity of the function is $O(n)$, and is $\Theta(n)$ when $L$ contains $n$ or more elements. If, for instance, $L$ only contains 1 element, then it is actually $\Theta(\log_{4}(n))$.
Find a lower bound (Big Ω) on the best case run time of the following code segment.
Carefully examine to see if this is a tight lower bound (Big θ)
string bigOh2(int n)
if(n == 0) return "a";
string str = bigOh2(n-1);
return str + str;
Answer: The time complexity of the function is $\Omega(n)$, where $n$ is the value of the integer provided as input. but it is not $\Theta(n)$ unless string concatenation is a constant time operation. Typically, string concatenation has a time complexity of $\Theta(n)$, where $n$ is the length of the string. In this case, the length of the string is $2^n$ giving this function a time complexity of $\Theta(2^n)$, where $n$ is the number provided to the function as input. The space complexity of the function is $\Theta(2^n)$ as well. Also, wouldn't this function never end if it was provided a negatively-valued integer as input?
In class, we discussed finding the shortest path between two vertices in a graph. Suppose instead we are interested in finding the longest simple path in a directed acyclic graph. In particular, I am interested in finding a path (if there is one) that visits all vertices. Given a DAG, give a linear-time algorithm to determine if there is a simple path that visits all vertices.
Answer: If a simple path visits all vertices, then there can only be one vertex with no inbound edges. If there are 2 vertices of this nature, then there is no path from one to the other. If there are 0 vertices of this nature, then the graph contains a cycle, and is thereby not a DAG. To solve this problem, start with the vertex with no inbound edges.
Finding a topological ordering is a procedure that can be achieved in linear time, with a time complexity of $\Theta(m+n)$, where $n$ is the number of vertices and $m$ is the number of edges.
If there exists exactly one topological ordering, then there is a simple path that visits all vertices.