• retagged by
2,569 views
3 3 votes

You are given a linked list, L, and another linked list, P, containing integers, sorted in ascending order. The operation print_lots(L,P) will print the elements in L that are in positions specified by P. For instance, if $P = 1, 3, 4, 6$, the first, third, fourth, and sixth elements in L are printed. If you write the routine function print_lots(L,P) where you should use only the basic list operations.  The running time of your routine function is ______________ ?

  1. $O( n^2 )$
  2. $O(n)$
  3. $O(n \log n)$
  4. $O(\log n)$

2 Answers

Best answer
5 5 votes
Both link list are sorted already. so no need to traverse any link multiple time. in link list access and traverse TC is O(n). what here we have to do is start traversing both list from initial node. as we move forwad in P list we get the positions in L list in asecending order, at which node we find required point and print it. as lists are sorted no need to traverse multiple time. so only in one traverse we get the output. so if list haas n elements, TC is O(n). so answer should be option B
• selected by
0 0 votes

Whatever P's contents are, we have to print L's content of that node.

Since P is sorted in increasing order, hence for any print action we never have to go back in L. In just one careful traverse we can do this.

So $O(n)$


A little more details:-

Assume P's contents are 3, 16, 49 and 200. (sorted in increasing order)

We have to print the contents of L located at node 3, node 16, node 49 and node 200.

So, max we need to go to 200, and this can happen in a single pass.

 

So, $O(n)$ // to traverse P

$+ O(1)$ // to traverse upto the last element specified by P, which will be some constant.

=> $O(n)+ O(1)=O(n)$

Answer:
Position:
Show:

Related questions

1 1 vote
1 answers 1 answer
981
981 views
Bikram asked Nov 26, 2016
981 views
The concatenation of $2$ lists is to be performed in $O(1)$ time. Which of the following implementations should be used?array implementation of listdoubly linked listsing...
1 1 vote
1 answers 1 answer
2.4k
2.4k views
Bikram asked Nov 26, 2016
2,365 views
Three algorithms do the same task. Algorithm One is $O(N)$ and Algorithm Two is $O(\log N)$ and Algorithm Three is $O(N1/2)$. Which algorithm should execute the fastest f...
2 2 votes
2 answers 2 answers
2.8k
2.8k views
Bikram asked Nov 26, 2016
2,804 views
Meena is working in an IT company as HR manager. She has a large list of potential candidates to be recruited which are all sorted by their names. But she found that due ...
2 2 votes
1 answers 1 answer
4.9k
4.9k views
Bikram asked Nov 26, 2016
4,904 views
Suppose you have the following set of keys to insert into a hash table that can hold $11$ values. $113, 117, 97, 100, 114, 108, 116, 105, 99$. Which of the following bes...