S Midsol
S Midsol
S Midsol
2. Use indicator random variables to nd the expected value of the number of xed elements (elements left in the same position) in a random permutation of n elements. Solution: Let Xi = 1 if the ith element is a xed element 0 otherwise
E(X) = E(
i=1
Xi ) =
i=1
E(Xi ) =
1 = 1. i=1 n
3. We have two input arrays, an array A with m elements and an array B with n elements, where m n. There may be duplicate elements. We want to decide if every element of B is an element of A. Describe an algorithm to solve this problem in O(n log m) worst-case time. Solution: First we sort A by MERGESORT (in O(m log m) time). Then for each element of B we do a binary search in the sorted list of A (in O(n log m) time). The total worst-case running time is O((m + n) log m) = O(n log m). 4. Assume that you want to sort an array of n numbers, each of which is a member of the set {0, 1, 2, 3, 4}. A sample input for n = 6 is (3, 1, 0, 3, 4, 3). Describe an optimal algorithm to solve this problem and prove that it is optimal; that is give a lower bound on the worst-case running time that has the same order of magnitude as the worst-case running time of your algorithm. Solution: This is just COUNTING-SORT with k = 4 with O(n) running time. We can give a linear time lower bound for solving the problem by observing that if an algorithm does not examine some element (examining all elements takes linear time), then this element may be changed by the adversary and the algorithm will give the same answer, which is now incorrect. 5. We have an input array A with n (n 2) numbers.
(a) Describe a O(n) worst-case time algorithm to nd two elements x, y A such that |x y| |u v| for all u, v A. (b) Describe a O(n log n) worst-case time algorithm to nd two elements x, y A such that |x y| |u v| for all u, v A. Solution: (a) For this we have to nd the minimum and the maximum simultaneously which we can do in 3 n/2 = O(n) time. (b) For this we sort the numbers rst, then x and y must be consecutive elements in the sorted order. We go through the sorted list and we nd the smallest dierence between two neighboring elements.