📄 | Weekly sheet
🗃️ | Materials
✨ | Tips and Tricks session
Complexity
1) The complexity of the following code is:
1
2
3
4
int a = 5;
int b = 7;
int c = 4;
int d = a + b + c + 153;
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n)$
$ c) \quad \mathcal{O}(nm)$
$ d) \quad \mathcal{O}(n^2)$
Answer
2) The complexity of the following code is:
1
2
3
for (int i = 1; i <= n; i++) {
// constant time code here
}
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n)$
$ c) \quad \mathcal{O}(n!)$
$ d) \quad \mathcal{O}(n^2)$
Answer
3) The complexity of the following code is:
1
2
3
4
5
int i = 0;
while (i < n) {
// constant time code here
i++;
}
$ a) \quad \mathcal{O}(n)$
$ b) \quad \mathcal{O}(1)$
$ c) \quad \mathcal{O}(nm)$
$ d) \quad \mathcal{O}(n^2)$
Answer
4) The complexity of the following code is:
1
2
3
for (int i = 1; i <= 5 * n + 17; i++) {
// constant time code here
}
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n^3)$
$ c) \quad \mathcal{O}(\sqrt{n})$
$ d) \quad \mathcal{O}(n)$
Answer
5) The complexity of the following code is:
1
2
3
4
5
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// constant time code here
}
}
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n)$
$ c) \quad \mathcal{O}(nm)$
$ d) \quad \mathcal{O}(n^2)$
Answer
6) The complexity of the following code is:
1
2
3
4
5
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
// constant time code here
}
}
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n)$
$ c) \quad \mathcal{O}(nm)$
$ d) \quad \mathcal{O}(n^2)$
Answer
7) The complexity of the following code is:
1
2
3
4
5
6
7
8
for (int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
// constant time code here
}
}
for (int i = 1; i <= n ; i++) {
// more constant time code here
}
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n)$
$ c) \quad \mathcal{O}(nm)$
$ d) \quad \mathcal{O}(n^2)$
Answer
8) The complexity of the following code is:
1
2
3
4
5
6
7
8
9
10
int n;
while(n > 0){
if(n % 2 == 0){
cout << 0;
}
else{
cout << 1;
}
n /= 2;
}
$ a) \quad \mathcal{O}(1)$
$ b) \quad \mathcal{O}(n)$
$ c) \quad \mathcal{O}(\log_{2}{n})$
$ d) \quad \mathcal{O}(n^2)$