Practice Questions on Time Complexity Analysis
Last Updated :
20 Nov, 2024
Prerequisite: Analysis of Algorithms
1. What is the time, and space complexity of the following code:
CPP
int a = 0, b = 0;
for (i = 0; i < N; i++) {
a = a + rand();
}
for (j = 0; j < M; j++) {
b = b + rand();
}
Java
int a = 0, b = 0;
for (i = 0; i < N; i++) {
a = a + Math.random();
}
for (j = 0; j < M; j++) {
b = b + Math.random();
}
Python
a = 0
b = 0
for i in range(N):
a = a + random()
for i in range(M):
b= b + random()
C#
Random rnd = new Random();
int a = 0, b = 0;
for (i = 0; i < N; i++) {
a = a + rnd.Next();
}
for (j = 0; j < M; j++) {
b = b + rnd.Next();
}
JavaScript
let a = 0, b = 0;
for (i = 0; i < N; i++) {
a = a + Math.random();
}
for (j = 0; j < M; j++) {
b = b + Math.random();
}
// This code is contributed by Aman Kumar
Options:
- 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
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)
2. What is the time complexity of the following code:
CPP
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
Java
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
Python
a = 0;
for i in range(N):
for j in reversed(range(i,N)):
a = a + i + j;
C#
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
JavaScript
let a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
// This code is contributed by Aman Kumar
Options:
- O(N)
- O(N*log(N))
- O(N * Sqrt(N))
- 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.
3. What is the time complexity of the following code:
CPP
int i, j, k = 0;
for (i = n / 2; i <= n; i++) {
for (j = 2; j <= n; j = j * 2) {
k = k + n / 2;
}
}
Java
int i, j, k = 0;
for (i = n / 2; i <= n; i++) {
for (j = 2; j <= n; j = j * 2) {
k = k + n / 2;
}
}
Python
k = 0;
for i in range(n//2,n):
for j in range(2,n,pow(2,j)):
k = k + n / 2;
C#
int i, j, k = 0;
for (i = n / 2; i <= n; i++) {
for (j = 2; j <= n; j = j * 2) {
k = k + n / 2;
}
}
JavaScript
let i=0, j=0, k = 0;
for (i = Math.floor(n / 2); i <= n; i++) {
for (j = 2; j <= n; j = j * 2) {
k = k + Math.floor(n / 2);
}
// This code is contributed by Aman Kumar
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).
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?
Options:
- 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
Output:
2. X will always be a better choice for large inputs
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.
5. What is the time complexity of the following code:
CPP
int a = 0, i = N;
while (i > 0) {
a += i;
i /= 2;
}
Java
int a = 0, i = N;
while (i > 0) {
a += i;
i /= 2;
}
Python
a = 0
i = N
while (i > 0):
a += i
i //= 2
C#
int a = 0, i = N;
while (i > 0) {
a += i;
i /= 2;
}
JavaScript
let a = 0, i = N;
while (i > 0) {
a += i;
i = Math.floor(i/2);
}
// This code is contributed by Aman Kumar
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)
6. Which of the following best describes the useful criterion for comparing the efficiency of algorithms?
- Time
- Memory
- Both of the above
- None of the above
3. Both of the above
Explanation: Comparing the efficiency of an algorithm depends on the time and memory taken by an algorithm. The algorithm which runs in lesser time and takes less memory even for a large input size is considered a more efficient algorithm.
7. How is time complexity measured?
- By counting the number of algorithms in an algorithm.
- By counting the number of primitive operations performed by the algorithm on a given input size.
- By counting the size of data input to the algorithm.
- None of the above
2. By counting the number of primitive operations performed by the algorithm on a given input size.
8. What will be the time complexity of the following code?
C++
for (int i = 1; i < n; i++) {
i *= k;
}
Java
for(int i=1;i<n;i++){
i*=k;
}
Python
# code
for i in range(n):
modified_i = i * k
C#
for(int i=1;i<n;i++){
i*=k;
}
JavaScript
for(var i=1;i<n;i++)
i*=k
- O(n)
- O(k)
- O(logkn)
- O(lognk)
Output:
3. O(logkn)
Explanation: Because the loop will run kc-1 times, where c is the number of times i can be multiplied by k before i reaches n. Hence, kc-1=n. Now to find the value of c we can apply log and it becomes logkn.
9. What will be the time complexity of the following code?
C++
int value = 0;
for(int i=0;i<n;i++)
for(int j=0;j<i;j++)
value += 1;
Java
int value = 0;
for(int i=0;i<n;i++)
for(int j=0;j<i;j++)
value += 1;
Python
value = 0;
for i in range(n):
for j in range(i):
value=value+1
C#
int value = 0;
for(int i=0;i<n;i++)
for(int j=0;j<i;j++)
value += 1;
JavaScript
var value = 0;
for(var i=0;i<n;i++)
for(var j=0;j<i;j++)
value += 1;
- n
- (n+1)
- n(n-1)/2
- n(n+1)
Output:
3. n(n-1)/2
Explanation: First for loop will run for (n) times and another for loop will be run for (n-1) times as the inner loop will only run till the range i which is 1 less than n , so overall time will be n(n-1)/2.
10. Algorithm A and B have a worst-case running time of O(n) and O(logn), respectively. Therefore, algorithm B always runs faster than algorithm A.
- True
- False
False
Explanation: The Big-O notation provides an asymptotic comparison in the running time of algorithms. For n < n0, algorithm A might run faster than algorithm B, for instance.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem