Tutorials
Understanding Algorithm Complexity
10 min read
Algorithm complexity is a fundamental concept in computer science that helps us understand how our code performs as input size grows. Let's explore this concept with practical examples.
Big O Notation
Big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows.
Common Time Complexities
- O(1) - Constant time
- O(log n) - Logarithmic time
- O(n) - Linear time
- O(n log n) - Log-linear time
- O(n²) - Quadratic time
- O(2ⁿ) - Exponential time
Examples in Code
O(1) - Constant Time
// Array access - O(1)
const array = [1, 2, 3, 4, 5];
const firstElement = array[0]; // Always takes the same time
// Object property access - O(1)
const user = { name: "John", age: 30 };
const userName = user.name; // Always takes the same time
O(n) - Linear Time
// Linear search - O(n)
function findElement(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
// Sum of array elements - O(n)
function sumArray(array) {
let sum = 0;
for (let num of array) {
sum += num;
}
return sum;
}
O(n²) - Quadratic Time
// Bubble sort - O(n²)
function bubbleSort(array) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap elements
[array[j], array[j + 1]] = [array[j + 1], array[j]];
}
}
}
return array;
}
Optimization Tips
Best Practices
- Use appropriate data structures for your use case
- Consider space-time tradeoffs
- Look for opportunities to reduce nested loops
- Use built-in methods when available (they're usually optimized)
- Profile your code to identify bottlenecks
Common Pitfalls
Understanding algorithm complexity helps you avoid common performance pitfalls in your code:
- Unnecessary nested loops
- Inefficient data structure choices
- Redundant calculations
- Memory leaks