Solutions to old final exam Problem 1 --------- public Map mystery(Map m) { Map x = new HashMap(); for(Object a : m.keySet()) { Object b = m.get(a); x.put(b, a); } return x; } The mystery problem takes a Map as input and returns a Map in which the key, value pairs are "reversed". For example, if the original mapped names to phone numbers, the new map would map phone numbers to names instead. A good name might be flipMap or reverseMap. Problem 2 --------- Problem 3 --------- part a) 50 / \ 30 80 \ / \ 40 60 90 / \ / 35 45 65 part b) 50 / \ 35 80 \ / \ 40 60 90 / 65 part c) 60 / \ 40 80 / \ / \ 35 50 65 90 Problem 4 --------- part a) The best case scenario would be when sorting an already sorted list. We'd make one pass over the "unsorted" region, conclude it was already sorted, and stop. Thus in the best case it's O(N). part b) Worst case would be a reverse-sorted list as input, so that the new algorithm was never able to stop "early". At each step, we'd therefore run our "is it sorted" pass, which is O(n), and then do the "find the smallest" pass, which is *also* O(n). Each sorting step would therefore be 2n instead of n. Since we have n sorting steps overall, that gives T(n)=2n^2 --> O(n^2). That's the same Big-O as the original, though with twice as many computational steps. Problem 5 --------- part a) O(N^2): We make a linear pass through the array, but for each value need to make another linear pass. It's true that we might get to stop early on some of those passes, but worst case it's still O(N^2) part b) Sorting takes O(N log N) time, and then we make a linear pass through as we look at adjacent items. The total is therefore the sum of the two passes, (N log N) + N, but we can drop the lower-order term, giving O(N log N). part c) We have N words to check. For each word we insert into a BST, which costs O(log N). Checking whether the word is already present doesn't take any extra time -- once we get to the right spot in the BST we check to see if that node contains the word we're trying to insert before (perhaps) adding it. Total cost is therefore O(N log N). part d) The operations on a HashSet are constant time. For each of the N words we do a constant-time "is it there" check, followed (perhaps) by a constant-time add. Worst case that's still just O(N).