Analyzing Time Complexity of algorithms
What is Time Complexity 🤷♂️
Time complexity is the way to describe how long our code might take to run as the amount of input increase. It doesn't measure actual time - it just provide the rough idea of how the performance growth.
Best Case → Ω (Omega)
Average Case → Θ (Theta)
Worst Case → O (Big-Oh)
🧠 Common Time Complexities
| Complexity | Description |
| O(1) | Constant time — Independent of input size |
| O(log n) | Logarithmic time |
| O(n) | Linear time |
| O(n²) | Quadratic time |
| O(2ⁿ), O(3ⁿ) | Exponential time |
| O(n!) | Factorial time |
int main() {
int x, y, z; ------------------> Line 1
z = x + y; ------------------> Line 2
return 0; ------------------> Line 3
}
Variables
x, y, zdeclaration takes constant time → let’s say T1.The operation
z = x + yis a simple arithmetic operation (addition), which also takes constant time → call it T2.
return 0is a simple return statement → constant time as well.Total Time Complexity = T1 + T2 = Constant Time =
0(1)
int main() {
int a, b, c, d, n; -------------------------> 0(1)
a = b + c; -------------------------> 0(1)
cin >> n; -------------------------> 0(1)
for(int i=0; i < n; i++) { -----------------> 0(n)
a++; -----------------------> 0(1)
}
}
Based on Previous example we can say that
input
a, b, c, d, ntaken constant time → T1simple operation and assigning process
a = b + ctake constant time → T2cin » nalso take constant time → T3for loop that run from
0 —> nby increasing order so the loop run maximum number of n timesThe inner operation of loop
a++take constant time → T4Total Time Complexity = T1 + T2 + T3 + n + T4 so the maximum time from this algo is 0(n)
int main() {
for(int i=0; i < n; i += 2) { ----------> n/2 = n
for(int j=0; j < n; j++) { ------> n * n
cout << "hello" ---------> n * n
}
}
return 0;
}
🔹Outer loop:
Starts from
i = 0and goes toi < n, incrementing byi += 2.
So total number of iterations =
n / 2(ignoring floor/ceil for big-O).In Big-O, we drop constants → this is O(n).
🔹 Inner loop:
For every value of
i, the inner loop runs fromj = 0toj < n, incrementing by 1.This loop runs n times → O(n).
🔹 Inner operation:
cout << "hello";is a constant time operation → O(1).Since it's inside the inner loop, it runs n times per outer loop iteration.
int main() {
for(int i=1; i < n; i *= 2) { ---------> log2n
cout << "Hello"
}
return 0;
}
Starts from
i = 0and goes toi < n, incrementing byi *= 2.so
i = 2^kin the k-th iteration.Time Complexity is
0(logn)
int main() {
for(int i=0; i < n; i++) { ----------------> n
for(int i=1; i < n; i *= 2) { ---------> n * log2n
cout << "Hello"
}
}
return 0;
}
Outer loop run
ntimesinner loop run
2^ktimes meanslog ntimeTotal Time Complexity = n * logn =
0(n log n)
Find Complexity in recursion code
Series of Time Complexity
O(1) < O(log n) < O(n) < O(n log n) < O(n^c) < O(cⁿ) < O(n!)
