What is the time complexity
int j = 0; for(int i = 0; i < n; ++i) { while(j < n && arr[i] < arr[j]) { j++; } }
Answer: O(n)
What is the time complexity
int j = 0; for(int i = 0; i < n; ++i) { while(j < n && arr[i] < arr[j]) { j++; } }
Answer: O(n)
These are the multiple choice questions. Please, try to understand why the answer is what it is. If you are stuck, ask in the comments.
n
is a positive integer. Answer: for (idx = 1; idx < n; idx *= 2)
for (idx = 0; idx < n; ++idx)
for (idx = 0; idx < n; idx += 2)
for (idx = 1; idx < n; idx *= 2)
for (idx = n; idx > -1; idx /= 2)
Identify the space and time complexity of the following chunks of code. I will post the answers later
int a = 0, i = N; while (i > 0) { a += i; i /= 2; }
Select here to see the answer: Time: O(log N), Space: O(1)
int count = 0; for (int i = N; i > 0; i /= 2) { for (int j = 0; j < i; j++) { count += 1; } }
Select here to see the answer: Time: O(N), Space: O(1)
int i, j, k = 0; for (i = n/2; i <= n; i++) { for (j = 2; j <= n; j = j * 2) { k = k + n/2; } }
Select here to see the answer: Time: Θ(n logn), Space: O(1)
int gcd(int n, int m) { if (n%m ==0) return m; if (n < m) swap(n, m); while (m > 0) { n = n%m; swap(n, m); } return n; }
Assume n > m
Select here to see the answer: Time: Θ(log n), Space: O(1)
Identify the space and time complexity of the following chunks of code. I will post the answers later
int a = 0, b = 0; for (i = 0; i < N; i++) { a = a + rand(); } for (j = 0; j < M; j++) { b = b + rand(); }
Select here to see the answer: Time: O(N+M), Space: O(1)
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; }
Select here to see the answer: Time: O(N2), Space: O(1)
int a = 0; for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; } }
Select here to see the answer: Time: O(N2), Space: O(1)