Prerequiste: Analysis of Algorithms
1. What is the time, space complexity of following code:
- O(N * M) time, O(1) space
- O(N + M) time, O(N + M) space
- O(N + M) time, O(1) space
- O(N * M) time, O(N + M) space
3. O(N + M) time, O(1) space
Explanation: The first loop is O(N) and the second loop is O(M). Since we don’t know which is bigger, we say this is O(N + M). This can also be written as O(max(N, M)).
Since there is no additional space being utilized, the space complexity is constant / O(1)
2. What is the time complexity of following code:
- O(N * Sqrt(N))
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
3. What is the time complexity of following code:
Explanation:If you notice, j keeps doubling till it is less than or equal to n. Number of times, we can double a number till it is less than n would be log(n).
Let’s take the examples here.
for n = 16, j = 2, 4, 8, 16
for n = 32, j = 2, 4, 8, 16, 32
So, j would run for O(log n) steps.
i runs for n/2 steps.
So, total steps = O(n/ 2 * log (n)) = O(n*logn)
4. What does it mean when we say that an algorithm X is asymptotically more efficient than Y?
- X will always be a better choice for small inputs
- X will always be a better choice for large inputs
- Y will always be a better choice for small inputs
- X will always be a better choice for all inputs
2. X will always be a better choice for large inputs
Explanation: In asymptotic analysis we consider growth of 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.
5. What is the time complexity of following code:
- O(N / 2)
- O(log N)
4. O(log N)
Explanation: We have to find the smallest x such that N / 2^x N
x = log(N)
- Time Complexity Analysis | Tower Of Hanoi (Recursion)
- Algorithms Sample Questions | Set 3 | Time Order Analysis
- Complexity Analysis of Binary Search
- Analysis of Algorithms | Set 5 (Practice Problems)
- A Time Complexity Question
- Time Complexity of Loop with Powers
- An interesting time complexity question
- Time Complexity of building a heap
- Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
- Understanding Time Complexity with Simple Examples
- Time complexity of recursive Fibonacci program
- Python Code for time Complexity plot of Heap Sort
- Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
- Analysis of Algorithm | Set 5 (Amortized Analysis Introduction)
- Analysis of Algorithms | Set 1 (Asymptotic Analysis)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.