Shift the successive elements thus overall big o

This preview shows page 2 - 4 out of 8 pages.

shift the successive elements . Thus overall Big-O notation is O(N)*O(N)=O(N^2). b. For Linked List, the elements in lst1 is N and lst2 is empty. It again takes O(N) for passing the for loop for each iterating through each element in lst1. As it is added in the beginning of the Linked List the Big-O for adding becomes constant O(1). Thus final running time is O(N)*O(1)=O(N) .
3. What is the Big-O running time of the following code fragment? public static void erase( List<Integer> lst ) { Iterator<Integer> itr = lst.iterator(); while ( itr.hasNext() ) { Integer x = itr.next(); itr.remove(); } } a. If an ArrayList is passed for lst. Explain your answer. b. If a LinkedList is passed for lst. Explain your answer. Solution :
The first element is removed, but the second element takes the place of the first element and so on. Thus making the time complexity O(N). Overall complexity turns out to be O(N)*O(N)=O(N^2) . b. In case of a Linked List deletion takes constant time as there is no shifting of previous elements. But the process will run until the list becomes empty. Thus passing N items. So overall complexity turns out to be O(1)*O(N)=O(N) . 4. What is the Big-O running time of the following code fragment? Assume lst1 has N items, and lst2 has N items. public static int Count( List<Integer> lst1, List<Integer> lst2)
a. If an ArrayList is passed for lst1 and lst2. Explain your answer. b. If a LinkedList is passed for lst1 and lst2. Explain your answer. Solution :

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture