Practice Questions on Time Complexity Analysis
Practice Questions on Time Complexity Analysis
int a = 0, b = 0;
a = a + Math.random();
b = b + Math.random();
Options:
1. O(N * M) time, O(1) space
2. O(N + M) time, O(N + M) space
3. O(N + M) time, O(1) space
4. O(N * M) time, O(N + M) space
Output:
3. O(N + M) time, O(1) space
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:
1. O(N)
2. O(N*log(N))
3. O(N * Sqrt(N))
4. O(N*N)
Output:
4. O(N*N)
Explanation:
The above code runs total no of times
= N + (N – 1) + (N – 2) + … 1 + 0
= N * (N + 1) / 2
= 1/2 * N^2 + 1/2 * N
O(N^2) times.
Explanation: We have to find the smallest x such that ‘(N / 2^x )< 1
OR 2^x > N’
x = log(N)