CS 141 Homework Assignment #2 Set Jan. 28, 2008 Due Feb. 11, 2008, before the midterm 1. [15+5 pts] [Levitin, pp. 106-107] Question 10. (The same exercise is also stated in Question 9 on page 106 of the 1st edition, although the specification is a bit brief.) Instead of writing a real computer program, for this exercise you need only write an informal algorithm in pseudocode. Let us assume that the input is an square matrix M(n,n) of letters. Also assume that you can check if a string x of letters is a legal English word using a Boolean function Word(x), which returns true if x is legal and false otherwise, in constant (i.e. Theta(1)) time. Analyze the time complexity of your algorithm using the Theta notation. 2. [15 pts] [Levitin, pp. 119] Question 6. (This is the Question 7 on p. 118 in the 1st edition of Levitin.) Let us assume that the input set A has n integers and is given to you as an array A[1..n]. Recall the bit vector representation of a set that you may have learned in CS 14 (also reviewed on p. 37 of Levitin). You may represent each subset of A as a bit vector of length n. You may also enumerate all the bit vectors by treating a bit vector as a binary number and repeatedly adding 1 to it. What is the time complexity of your algorithm, assuming that incrementing a bit vector by 1 takes Theta(n) time in the worst case? 3. [20 pts] Let A[1..n] be an array of n distinct numbers. If i < j and A[i] > A[j], then the pair (i,j) is called an inversion in A. a. List the five inversions in the array <2,3,8,6,1>. b. What array with elements from the set {1,2, ..., n} has the most inversions? How many does it have? c. Write an algorithm that determines the number of inversions in any permutation of n elements in O(nlog n) time in the worst case. (Hint: Modify Mergesort.) Analyze the time complexity of your algorithm in part c. 4. [10 pts] [Levitin, pp. 171-172] Question 8(b). (Question 8(b) on p. 169 in the 1st edition.) How should the input graph be represented and what is the time complexity of your algorithm? 5. [10 pts] Let G = (V,E) be a DAG, where |V| = n and |E| = m. A vertex v is called a sink of G if there is a path from every vertex in G to v. A DAG may or may not have a sink in general. Design an O(n+m) time algorithm to check if G has a sink, assuming that G is represented as adjacency lists. Hint: A DAG may have at most one sink. Use topological sorting or a simple modification of the source-removal algorithm on page 175. (pp. 172-173 in the 1st edition.) 6. [Optional, 10 bonus pts] [Levitin, p. 135] Question 11. (Question 10 on p. 133 in the 1st edition.) You do not have to give a formal analysis (or proof) of the Theta(nlog n) time complexity of your algorithm, but you need give some reasonable argument. For example, you may compare the steps in your algorithm with those in Quicksort. You may also assume that the each given bolt uniquely matches a nut (i.e., its corresponding nut).