Big O notation is a fundamental concept in computer science that describes the efficiency of algorithms. Here are common examples of time complexity:
Constant Time - O(1)
# Accessing an element in an array
arr = [1, 2, 3]
value = arr[0] # O(1)
Linear Time - O(n)
// Traversing an array
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]); // O(n)
}
Quadratic Time - O(n²)
// Nested loop example
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
// O(n²)
}
}
Logarithmic Time - O(log n)
// Binary search example
while (low <= high) {
mid = (low + high) / 2; // O(log n)
}
Log-Linear Time - O(n log n)
# Merge sort example
def merge_sort(arr)
# O(n log n)
end
Exponential Time - O(2ⁿ)
// Recursive Fibonacci example
func fibonacci(n: Int) -> Int {
if n <= 1 { return n }
return fibonacci(n: n-1) + fibonacci(n: n-2) // O(2ⁿ)
}
For deeper understanding, check our Time Complexity guide. 📚