7-Time & Space complexity-23-07-2024
7-Time & Space complexity-23-07-2024
Calculate )
Operation
O (n log
Time
n)
s
Complexity O(n)
Element
s
What is Time Complexity?
Topic/Course
You can get the time complexity by “counting” the number of operations performed by your
code.
This time complexity is defined as a function of the input size n using Big-O notation. n indicates
the input size, while O is the worst-case scenario growth rate function.
We use the Big-O notation to classify algorithms based on their running time or space (memory
used) as the input grows.
Calculate )
Operation
O (n log
Time
n)
s
Complexity O(n)
Element
s
Big O Cheatsheet
Big OTopic/Course
Notation Name Examples
int fun()
{
for(i = 1; i < n; i++)
{
cout << “FACE PREP”;
}
return 0;
}
int fun()
{
for(i = 1; i <= sqrt(n); i++)
{
cout << “FACE PREP”;
}
return 0;
}
int fun()
{
for(i = 1; i*i <= n; i++)
{
cout << “FACE PREP”;
}
return 0;
}
int fun()
{
for(i = 1; i <= n; i=i*2)
{
cout << “FACE PREP”;
}
return 0;
}
int fun()
{
int n;
while(n > 1)
{
n = n / 2;
}
return 0;
}
int fun()
{
for(i = 1; i < n; i++)
{
for(j = 1; j < n; j++)
{
cout << “FACE PREP”;
}
}
return 0;
}
int fun()
{
for(i = 1; i < n; i++)
{
for(j = 1; j < n; j=j+i)
{
cout << “FACE PREP”;
}
}
return 0;
}
int fun()
{
int i, j;
for(i = 1; i < n; i++)
{
for(j = 1; j < n; j=j*2)
{
cout << “FACE PREP”;
}
}
return 0;
}
A) O(n) B) O(log n) C) O (n * log D) O(n * n)
n)
Predict the time complexity for the given below code snippet
int fun()
{
int i, j;
for(i = 1; i < n; i++)
{
for(j = n; j > 1; j--)
{
cout << “FACE PREP”;
}
}
}
int fun()
{
int i, j, a = 0, b = 0;
return 0;
}
int fun()
{
int n, ans = 0;
cin >> n;
while(n > 0)
{
ans += n % 10;
n /= 10;
}
return 0;
}
A) O(n) B) O(log n) C) O (n * n)
D) O(n^2 (log
Predict the time complexity for the given below code snippet
int fun(int n)
{
if(n > 1)
return fun(n – 1);
}
int fun()
{
for(i = 1; i < n; i++)
{
for(j = 1; j < sqrt(n); j++)
{
cout << “FACE PREP”;
}
}
return 0;
}
int fun()
{
int n, i = 1, s = 1;
while(s <= n)
{
i++;
s = s + i;
cout << “FACE PREP”;
}
return 0;
}