What is Time Complexity?
Time complexity is the measure of efficiency of an algorithm as the size of the input grows.
It tells us how many operations an algorithm takes to complete, depending on input size n.
π‘ Myth: Time complexity β Time taken
β Fact: Time taken depends on machine, language, and environment.
β Time complexity is theoreticalβit gives a general idea of algorithm performance.
What is an Algorithm?
An algorithm is simply a step-by-step solution to a problem.
Key Insight:
Lower time complexity = Better performance
So we prefer algorithms with less complexity when solving problems.
π Example: Linear Search vs Binary Search
Linear Search:
Works on both sorted and unsorted arrays
Time Complexity: O(n)
Example:
// array = [2, 3, 4, 5, 6]
// Find 4 by looping through each element
Binary Search:
Works only on sorted arrays
Time Complexity: O(log n)
Example:
// array = [2, 3, 4, 5, 6]
// Start with middle, divide in half repeatedly
Feature Linear Search Binary Search
Input Requirement Sorted/Unsorted Sorted only
Approach Loop through each Divide & conquer
Time Complexity O(n) O(log n)
β Binary Search is faster and more efficient than Linear Search on sorted data.
π§ Common Time Complexities (With Examples):
O(1) β Constant Time
Example: arr5
O(log n) β Logarithmic Time
Example: Binary Search
O(n) β Linear Time
Example: Linear Search
O(n log n) β Linearithmic Time
Example:
for (i = 0; i < n; i++) {
binarySearch();
}
O(nΒ²) β Quadratic Time
Example: Nested loops (e.g., bubble sort)
O(nΒ³) β Cubic Time
Example: Three nested loops
O(2βΏ) β Exponential Time
Example: Recursive Fibonacci
O(n!) β Factorial Time
Example: Generating all permutations
β οΈ Note: O(2βΏ) and O(n!) are rarely used because they're very inefficient.
πΊ Time Complexity Graph:
Hereβs a visual graph representing different complexities from best to worst:
Time Complexity Graph
Final Time Complexity Ranking:
O(1) < O(log n) < O(n) < O(n log n) < O(nΒ²) < O(2βΏ) < O(n!)
Top comments (0)