What is the time complexity of the following code : int a = 0; for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; } }
Question
What is the time complexity of the following code : int a = 0; for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; } }
Solution
The time complexity of the given code is O(N^2).
Here's why:
- The outer loop runs N times, where N is the input size.
- For each iteration of the outer loop, the inner loop runs N - i times, where i is the current iteration of the outer loop.
- The number of operations that the inner loop performs is proportional to the number of times it runs. Therefore, the total number of operations is the sum of the series 1 + 2 + 3 + ... + N, which is (N*(N+1))/2.
- This sum is proportional to N^2, so the time complexity of the code is O(N^2).
Similar Questions
What is the time complexity of the following code? for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { System.out.println(i * j); } } a. O(n) b. O(2^n) c. O(n^2) d. O(n log n)
What is the time complexity of the following code :int i, j, k = 0;for (i = n/2; i <= n; i++) { for (j = 2; j <= n; j = j * 2) { k = k + n/2; }}
What is the time complexity of the following code : int a = 0, i = N; while (i > 0) { a += i; i /= 2; }
What is the time complexity of the following code fragment?for(i=1; i<n; i= i*2) a[i]=0;
What is the time, space complexity of following code :int a = 0, b = 0; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { a = a + j; } } for (k = 0; k < N; k++) { b = b + k; }
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.