Question
Problem 1 Consider the following method, which takes two unsorted lists, list1, and list2 both instances of our LLList class from the lecture and creates
Problem 1
Consider the following method, which takes two unsorted lists, list1, and list2 both instances of our LLList class from the lecture and creates a third list containing the intersection of list1 and list2:
public static LLList intersect(LLList list1, LLList list2) { LLList inters = new LLList();
for (int i = 0; i < list1.length(); i++) { Object item1 = list1.getItem(i); for (int j = 0; j < list2.length(); j++) { Object item2 = list2.getItem(j); if (item2.equals(item1)) { inters.addItem(item2, inters.length()); break; // move onto the next item from list1 } } }
return inters;
}
The lists are unsorted, so we take a nested-loop approach in which each item in list1 is compared to the items in list2; if a match is found in list2, the item is added to the intersection and we break out of the inner loop. (Note that this method will include duplicate values in the intersection when list1 itself has duplicates; doing so is acceptable for the purposes of this problem.)
i. What is the worst-case running time of this algorithm as a function of the length m of list1 and the length n of list2? Dont forget to take into account the time efficiency of the underlying list operations, getItem() and addItem(). Use big-O notation, and explain your answer briefly.
ii. Rewrite this method to improve its time efficiency. Your new method should not modify the existing lists in any way, and it should use no more than a constant (O(1)) amount of additional memory. Make the new method as efficient time-wise as possible, given the constraints on memory usage. You should assume this method is not part of the LLList class, and therefore it doesnt have direct access to the private LLList members.
iii. What is the worst-case running time of the improved algorithm? Use big-O notation, and explain your answer briefly.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started