I'm trying to find the Big-O complexity of the following algorithm:
int i, j;
for (i = 0; i < n; i += 5)
{
for (j = 1; j < n; j *= 3)
{
// O(1) code here
}
}
n is the size of an array passed into the method. Struggling with this due to the i += 5 and j *= 3. I know this is probably wrong but I tried the following...
Outer loop iterates n/5 times. Is that just O(n)?
Inner loop iterates log3(n) times. Must be just log(n).
Since they're nested, multiply the complexities together.
So the Big O complexity is just O(n log(n))?
You can proceed like the following:
Yes you are right. the time complexity is n(log n) -- base 3.
Try taking a very large input value for n and you will understand that the graph for [(n/5)*(log3n)]works identical. Hope this helps.
Related
for(i=0; i<n; i++) // time complexity n+1
{
k=1; // time complexity n
while(k<=n) // time complexity n*(n+1)
{
for(j=0; j<k; j++) // time complexity ??
printf("the sum of %d and %d is: %d\n",j,k,j+k); time complexity ??
k++;
}
What is the time complexity of the above code? I stuck in the second (for) and i don't know how to find the time complexity because j is less than k and not less than n.
I always having problems related to time complexity, do you guys got some good article on it?
especially about the step count and loops.
From the question :
because j is less than k and not less than n.
This is just plain wrong, and I guess that's the assumption that got you stuck. We know what values k can take. In your code, it ranges from 1 to n (included). Thus, if j is less than k, it is also less than n.
From the comments :
i know the the only input is n but in the second for depends on k an not in n .
If a variable depends on anything, it's on the input. j depends on k that itself depends on n, which means j depends on n.
However, this is not enough to deduce the complexity. In the end, what you need to know is how many times printf is called.
The outer for loop is executed n times no matter what. We can factor this out.
The number of executions of the inner for loop depends on k, which is modified within the while loop. We know k takes every value from 1 to n exactly once. That means the inner for loop will first be executed once, then twice, then three times and so on, up until n times.
Thus, discarding the outer for loop, printf is called 1+2+3+...+n times. That sum is very well known and easy to calculate : 1+2+3+...+n = n*(n+1)/2 = (n^2 + n)/2.
Finally, the total number of calls to printf is n * (n^2 + n)/2 = n^3/2 + n^2/2 = O(n^3). That's your time complexity.
A final note about this kind of codes. Once you see the same patterns a few times, you quickly start to recognize the kind of complexity involved. Then, when you see that kind of nested loops with dependent variables, you immediately know that the complexity for each loop is linear.
For instance, in the following, f is called n*(n+1)*(n+2)/6 = O(n^3) times.
for (i = 1; i <= n; ++i) {
for (j = 1; j <= i; ++j) {
for (k = 1; k <= j; ++k) {
f();
}
}
}
First, simplify the code to show the main loops. So, we have a structure of:
for(int i = 0; i < n; i++) {
for(int k = 1; k <= n; k++) {
for(int j = 0; j < k; j++) {
}
}
}
The outer-loops run n * n times but there's not much you can do with this information because the complexity of the inner-loop changes based on which iteration of the outer-loop you're on, so it's not as simple as calculating the number of times the outer loops run and multiplying by some other value.
Instead, I would find it easier to start with the inner-loop, and then add the outer-loops from the inner-most to outer-most.
The complexity of the inner-most loop is k.
With the middle loop, it's the sum of k (the complexity above) where k = 1 to n. So 1 + 2 + ... + n = (n^2 + n) / 2.
With the outer loop, it's done n times so another multiplication by n. So n * (n^2 + n) / 2.
After simplifying, we get a total of O(n^3)
The time complexity for the above code is : n x n x n = n^3 + 1+ 1 = n^3 + 2 for the 3 loops plus the two constants. Since n^3 carries the heaviest growing rate the constant values can be ignored, so the Time complexity would be n^3.
Note: Take each loop as (n) and to obtained the total time, multiple the (n) values in each loop.
Hope this will help !
I have an array of lists(i.e. each cell in the array contains a list). The length of the array is n and the sum of all the lengths of all the lists is k
I want to iterate over all the list elements(in the whole array):
for(int i = 0; i < n; ++i) {
for(int j = 0; j < array[i].list.Length(); ++j) {
//do something in O(1)
}
}
NOTE the inner loop runs less than k times per an iteration of the outer loop, but the total iterations it does for all the i is k
QuestionDoes the time complexity of the code is O(n + k)? Or would it be O(n*k)?
Question Does the time complexity of the code is O(n + k)? Or would it be O(n*k)?
Neither.
The complexity is O(n + k). In the case where n <= k, this would equal O(k), but this is not necessarily the case.
n <= k (original answer)
If the sum of all lengths is k, then, if you don't do anything else in the outer loop, the running time would be O(k). n is irrelevant in this case, since there is nothing interesting you're doing n times. Your data just happens to be split up in n chunks.
On average, each list's size would be k/n. That makes the time complexity of the algorithm O(n * k/n) which results in O(k).
n > k
In the case that n is larger than k, n becomes relevant since work has to be done each time, even if it's only checking the Length() of array[i]. Because of that, in this case the complexity is O(n + k).
Update
As Jordi Vermeulen correctly points out in the comments, my original answer that only took into consideration the case where n <= k is incomplete incorrect. The answer has been edited accordingly.
This is O(n + k), which is O(k) when n is O(k). This is, however, not necessarily the case (as suggested in the answer by Bart van Nierop). Consider, for instance, the case where n = k2. The loop is still running k2 times, so you can't say the complexity is O(k), even though in many iterations no work will be done other than increasing the counter.
For every i of the external loop, the inner loop is run array[i].list.Length() which you say is k:
k times + -+
k times + |
... |
... +--- n times
... |
k times -+
So the resulting time is O(n * k)
You should use n*k.
Foreach cols, process each lines.
You've got to do a loop (for or foreach) over each columns (n).
And then inside the n loop, you do another loop (for or foreach) that process each rows (k).
for (int i = 0; i < n; i++) {
for (int j = 0; j < array[i].list.length(); j++) {
// do something with array[i][j]
}
}
O(k).do something part will occur k times.
n is irrelevant in this case.
Basically I am struggling to come to grips with operation counting and Big-O notation. I understand it is possibly one of the harder parts of computer science to understand and I have to admit I am struggling with it. Could anyone give me some help with these examples, and possibly any further help/links with Big-O?
for (i = 0; i < N; i++)
{ for (j = i; j < N; j++)
{ sequence of statements }
}
Here I would say the complexity is O(N²) - Quadratic
int m = -9
for (j = 0; j < n; j+=5)
{
if (j<m)
{
for (k = 1; k <n; k*=3)
{some code}
}
}
Here I would also say is O(N²). The first loop takes N and the second loop takes N so I would say the answer is O(N*N) which is equal to O(N²).
Any help and advice for further understanding would be great!!
The first is indeed O(n^2), as you suspected, assuming the 'sequence of statements' is O(1).
However, the second part of code is O(n), since the condition j < m is never met - and thus, the outer loop only iterates itself without actually doing nothing. The inner loop is not even reachable.
As side note, some compilers may actually optimize the second part of code to run in O(1) by just setting the end values of variables, but this is not the point of the question.
The second example is complexity O(N).
int m = -9
for (j = 0; j < n; j+=5)
{
if (j<m)
{
// this never executes; m is negative and j is positive
}
}
First example:
The inner loop executes N times when i = 0, N-1 times when i = 1, and so on...
You can just calculate the number of steps the for loops execute
(N) + (N - 1) + (N - 2) + ... + 2 + 1
steps = N(N+1)/2 = (N^2 + N) / 2
N <=> 1 |add the left to the right| => N+1
(N - 1) <=> 2 |add the left to the right| => N+1
(N - 2) <=> 3 |add the left to the right| => N+1 . . . N
What does the big-O nation means?
F(N) = O(G(N)) means that |F(N)|<= c*|G(N)| where c > 0
It means that the G(N) function is an upper bound on the grothw rate of the function. F(N) could not grow faster than G(N).
Just to throw this out here: if we assume that the j<-9 clause is a mistake and ignore it, then your second example has two nested loops. However the inner loop is actually multiplying k times 3. So this makes this inner loop O(log n). Which makes the pair of loops O(n log n). I'm not sure this is the answer, but you asked for further understanding, so... you know... maybe that's further.
Ok, also on a further note I would really suggest you to go through a single lecture in the series of introduction of algorithms. Believe me you won't need to look any further.
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/
It's diffcult for me to understand logarithmic complexity of algorithm.
For example
for(int j=1; j<=n; j*=2){
...
}
Its complexity is O(log2N)
So what if it is j*=3? The complexity will then be O(log3N)?
You could say yes as long as the loop body is O(1).
However, note that log3N = log2N / log23, so it is also O(log2N), since the constant factor does not matter.
Also note it is apparent from this argument, for any fixed constant k, O(logkN) is also O(log2N), since you could substitute 3 with k.
Basicly, yes.
Let's assume that your for loop looks like this:
for (int j = 1; j < n; j *= a) {...}
where a is some const.
If the for loop executes k times, then in the last iteration, j will be equal to ak. And since N = O(j) and j = O(ak), N = O(ak). It follows that k = O(logaN). Once again, for loop executes k times, so time complexity of this algorithm is O(k) = O(logaN).
What is the complexity given for the following problem is O(n). Shouldn't it be
O(n^2)? That is because the outer loop is O(n) and inner is also O(n), therefore n*n = O(n^2)?
The answer sheet of this question states that the answer is O(n). How is that possible?
public static void q1d(int n) {
int count = 0;
for (int i = 0; i < n; i++) {
count++;
for (int j = 0; j < n; j++) {
count++;
}
}
}
The complexity for the following problem is O(n^2), how can you obtain that? Can someone please elaborate?
public static void q1E(int n) {
int count = 0;
for (int i = 0; i < n; i++) {
count++;
for (int j = 0; j < n/2; j++) {
count++;
}
}
}
Thanks
The first example is O(n^2), so it seems they've made a mistake. To calculate (informally) the second example, we can do n * (n/2) = (n^2)/2 = O(n^2). If this doesn't make sense, you need to go and brush up what the meaning of something being O(n^k) is.
The complexity of both code is O(n*n)
FIRST
The outer loop runs n times and the inner loop varies from 0 to n-1 times
so
total = 1 + 2 + 3 + 4 ... + n
which if you add the arithmetic progression is n * ( n + 1 ) / 2 is O(n*n)
SECOND
The outer loop runs n times and the inner loop varies from 0 to n-1/2 times
so
total = 1 + 1/2 + 3/2 + 4/2 ... + n/2
which if you add the arithmetic progression is n * ( n + 1 ) / 4 is also O(n*n)
First case is definitely O(n^2)
The second is O(n^2) as well because you omit constants when calculate big O
Your answer sheet is wrong, the first algorithm is clearly O(n^2).
Big-Oh notation is "worst case" so when calculating the Big-Oh value, we generally ignore multiplications / divisions by constants.
That being said, your second example is also O(n^2) in the worst case because, although the inner loop is "only" 1/2 n, the n is the clear bounding factor. In practice the second algorithm will be less than O(n^2) operations -- but Big-Oh is intended to be a "worst case" (ie. maximal bounding) measurement, so the exact number of operations is ignored in favor of focusing on how the algorithm behaves as n approaches infinity.
Both are O(n^2). Your answer is wrong. Or you may have written the question incorrectly.