Big O Notation
Table of Contents
Big O Notation
Overview
Big O notation is a mathematical notation used in computer science to describe the performance or complexity of an algorithm. It helps us understand how the runtime (time complexity) or memory usage (space complexity) of an algorithm scales as the input size (n) grows.
Essentially, Big O provides a high-level analysis, focusing on the "worst-case scenario" to predict how an algorithm will behave with very large inputs. This is crucial for building scalable and efficient applications.
Key Principles
- Focus on Growth, Not Exact Time: Big O isn't about measuring seconds or milliseconds. It's about understanding the rate of growth. An algorithm with O(n) complexity will see its runtime grow linearly with the input, while an O(n²) algorithm's runtime will grow quadratically.
- Worst-Case Analysis: It describes the upper bound of an algorithm's performance. For example, when searching for an item in a list, the worst case is that the item is the very last one you check.
- Simplification: To make analysis simpler, we drop constants and non-dominant terms.
- O(2n) becomes O(n) because the *2 doesn't change the fact that the growth is linear.
- O(n² + n) becomes O(n²) because as n becomes very large, the n² term is overwhelmingly more significant than the n term.
Common Big O Complexities
Here are some of the most common complexities, ordered from most to least efficient:
- O(1)—Constant Time: The algorithm takes the same amount of time regardless of the input size.
- O(log n)—Logarithmic Time: The runtime grows logarithmically. These algorithms are very efficient because the time it takes increases by a constant amount each time the input size is doubled.
- O(n)—Linear Time: The runtime is directly proportional to the input size. If the input size doubles, the runtime also doubles.
- O(n log n)—Linearithmic Time: A common complexity for efficient sorting algorithms. It's a combination of linear and logarithmic growth.
- O(n²)—Quadratic Time: The runtime is proportional to the square of the input size. This is common in algorithms that involve nested iterations over the input data.
- O(2ⁿ)—Exponential Time: The runtime doubles with each new element added to the input. These algorithms become impractical very quickly as the input size grows.
- O(n!)—Factorial Time: The runtime grows by a factorial of the input size. These are the slowest and most inefficient algorithms.
Criticisms of Big O
Big O always needs to be seen in context. Depending on data size Algorithms with a higher big O can be faster