Time and Complexity Based Practise Questions
Time and Complexity Based Practise Questions
int a = 0, b = 0;
a = a + rand();
b = b + rand();
Options:
Output:
Explanation: The first loop is O(N) and the second loop is O(M). Since N and M are independent
variables, so we can’t say which one is the leading term. Therefore Time complexity of the given
problem will be O(N+M).
Since variables size does not depend on the size of the input, therefore Space Complexity will
be constant or O(1)
int a = 0;
a = a + i + j;
Options:
O(N)
O(N*log(N))
O(N * Sqrt(N))
O(N*N)
Output:
4. O(N*N)
Explanation:
= N + (N – 1) + (N – 2) + … 1 + 0
= N * (N + 1) / 2
O(N^2) times.
int i, j, k = 0;
for (j = 2; j <= n; j = j * 2) {
k = k + n / 2;
Options:
O(n)
O(N log N)
O(n^2)
O(n^2Logn)
Output:
2. O(nLogn)
Explanation: If you notice, j keeps doubling till it is less than or equal to n. Several times, we can
double a number till it is less than n would be log(n).
4. What does it mean when we say that an algorithm X is asymptotically more efficient than Y?
Options:
Output:
Explanation: In asymptotic analysis, we consider the growth of the algorithm in terms of input
size. An algorithm X is said to be asymptotically better than Y if X takes smaller time than y for all
input sizes n larger than a value n0 where n0 > 0.
int a = 0, i = N;
while (i > 0) {
a += i;
i /= 2;
Options:
O(N)
O(Sqrt(N))
O(N / 2)
O(log N)
Output:
4. O(log N)
Explanation: We have to find the smallest x such that ‘(N / 2^x )< 1 OR 2^x > N’
x = log(N)