// assume 'n' is given. What is the time complexity of this code ?
java.util.LinkedList<Integer> k = new java.util.LinkedList<Integer>();
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
k.add(k.size()/2,j);
// assume 'n' is given. What is the time complexity of this code ?
java.util.LinkedList<Integer> k = new java.util.LinkedList<Integer>();
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
k.add(k.size()/2,j);
See, the first two times, the function $add(,)$ adds to 1st of list. Next two times it skips 1 element. Next two elements it has to skip 2 elements. So the number of steps goes like this:
$1+1+2+2+3+3+...$(Total of $n^2$ terms as there are two for loops) $=2(1+2+3+...+\frac{n^2}{2})$
$=\frac{n^2}{2}(\frac{n^2}{2}+1)\in \Theta(n^4)$
Hence time complexity is $\Theta(n^4)$
NOTE Here we make the assumption that adding in a linked list means going through the elements of the list. Assuming an oracle can add to the list in constant time we will get $\Theta(n^2)$complexity though.
The question cannot be answered at all. There are obviously $n^2$ calls to a function k.add(), but we have no idea whatsoever what the execution time of that function is. If it is implemented in a very simplistic manner then the way it is called may take $\Theta (n^2)$ steps on average for a total of $\Theta (n^4)$ operations.
If I had to implement this class LinkedList as a single linked list, I would keep two pointers in the list, one to some element close to the end of the list, and one to some element close to the place where the last insertion happened that wasn't at the very start or end. That way insertions, deletions and indexed access close to the beginning, close to the end, and near to the last location can be done in constant time. Since these are the typical uses, that should make the average must faster. In this case, such an implementation could easily lead to a $\Theta (n^2)$ total.
Assuming the basic operation is the k.add()
considering this section, say sectionA.
for(int j = 0;j<n;j++)
k.add(k.size()/2,j);
k.add() gets executed n-times. O(n)
consider the full case.
for(int i = 0;i<n;i++)
sectionA.
sectionA get executed n-times O(n).O(n)
== O(n^2)
. And hence the program has complexity O(n^2)
.
I think it is O(n^2) as there is a nested loop.
Edit:
If we take the loop body also into account, the complexity would be O(n^3) as the add() function takes O(j) time to insert an element to a linked list (j < n)
It is something like this,
java.util.LinkedList<Integer> k = new java.util.LinkedList<Integer>();
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
{
//another loop with O(j) complexity to add element
}
I still don't get how it's O(n^4). Could you explain little detail
add
method does? – Yuval Filmus May 30 '17 at 21:22