2.3 Time complexity¶
Running time gives us a direct, precise measure of an algorithm's efficiency. How might we predict exactly how long a piece of code will take?
- Specify the platform, including the hardware, programming language, and system environment. All of these affect execution speed.
- Estimate the time for each kind of operation. For example, suppose addition
+takes 1 ns, multiplication*takes 10 ns, and a print operationprint()takes 5 ns. - Count all the operations in the code and add up their execution times to get the running time.
For example, the following code has input size \(n\):
Using the method above, we get a running time of \((6n + 12)\) ns:
In practice, working out running time this way is neither desirable nor realistic. First, we want our estimate to apply across platforms, since an algorithm may run on many different machines. Second, finding the execution time of each operation is difficult, which makes the estimate hard to produce.
2.3.1 How running time grows¶
Time complexity analysis looks beyond an algorithm's elapsed time to how that time grows as the input gets larger.
To make this idea concrete, consider three algorithms, A, B, and C, each with input size \(n\):
// Time complexity of algorithm A: constant
void algorithm_A(int n) {
cout << 0 << endl;
}
// Time complexity of algorithm B: linear
void algorithm_B(int n) {
for (int i = 0; i < n; i++) {
cout << 0 << endl;
}
}
// Time complexity of algorithm C: constant
void algorithm_C(int n) {
for (int i = 0; i < 1000000; i++) {
cout << 0 << endl;
}
}
// Time complexity of algorithm A: constant
void algorithm_A(int n) {
System.out.println(0);
}
// Time complexity of algorithm B: linear
void algorithm_B(int n) {
for (int i = 0; i < n; i++) {
System.out.println(0);
}
}
// Time complexity of algorithm C: constant
void algorithm_C(int n) {
for (int i = 0; i < 1000000; i++) {
System.out.println(0);
}
}
// Time complexity of algorithm A: constant
void AlgorithmA(int n) {
Console.WriteLine(0);
}
// Time complexity of algorithm B: linear
void AlgorithmB(int n) {
for (int i = 0; i < n; i++) {
Console.WriteLine(0);
}
}
// Time complexity of algorithm C: constant
void AlgorithmC(int n) {
for (int i = 0; i < 1000000; i++) {
Console.WriteLine(0);
}
}
// Time complexity of algorithm A: constant
func algorithm_A(n int) {
fmt.Println(0)
}
// Time complexity of algorithm B: linear
func algorithm_B(n int) {
for i := 0; i < n; i++ {
fmt.Println(0)
}
}
// Time complexity of algorithm C: constant
func algorithm_C(n int) {
for i := 0; i < 1000000; i++ {
fmt.Println(0)
}
}
// Time complexity of algorithm A: constant
function algorithm_A(n) {
console.log(0);
}
// Time complexity of algorithm B: linear
function algorithm_B(n) {
for (let i = 0; i < n; i++) {
console.log(0);
}
}
// Time complexity of algorithm C: constant
function algorithm_C(n) {
for (let i = 0; i < 1000000; i++) {
console.log(0);
}
}
// Time complexity of algorithm A: constant
function algorithm_A(n: number): void {
console.log(0);
}
// Time complexity of algorithm B: linear
function algorithm_B(n: number): void {
for (let i = 0; i < n; i++) {
console.log(0);
}
}
// Time complexity of algorithm C: constant
function algorithm_C(n: number): void {
for (let i = 0; i < 1000000; i++) {
console.log(0);
}
}
// Time complexity of algorithm A: constant
void algorithmA(int n) {
print(0);
}
// Time complexity of algorithm B: linear
void algorithmB(int n) {
for (int i = 0; i < n; i++) {
print(0);
}
}
// Time complexity of algorithm C: constant
void algorithmC(int n) {
for (int i = 0; i < 1000000; i++) {
print(0);
}
}
// Time complexity of algorithm A: constant
fn algorithm_A(n: i32) {
println!("{}", 0);
}
// Time complexity of algorithm B: linear
fn algorithm_B(n: i32) {
for _ in 0..n {
println!("{}", 0);
}
}
// Time complexity of algorithm C: constant
fn algorithm_C(n: i32) {
for _ in 0..1000000 {
println!("{}", 0);
}
}
// Time complexity of algorithm A: constant
void algorithm_A(int n) {
printf("%d", 0);
}
// Time complexity of algorithm B: linear
void algorithm_B(int n) {
for (int i = 0; i < n; i++) {
printf("%d", 0);
}
}
// Time complexity of algorithm C: constant
void algorithm_C(int n) {
for (int i = 0; i < 1000000; i++) {
printf("%d", 0);
}
}
Figure 2-7 illustrates the time complexity of these three functions.
- Algorithm
Aperforms only \(1\) print operation. Its running time stays the same as \(n\) increases. We say it runs in constant time. - Algorithm
Brepeats the print operation \(n\) times. Its running time grows linearly with \(n\), so we say it runs in linear time. - Algorithm
Crepeats its print operation \(1000000\) times. Although it takes a long time, that time is independent of input size \(n\). ThusChas the same time complexity asA: constant time.
Figure 2-7 Running time growth for algorithms A, B, and C
Description of Figure 2-7: Algorithms A, B, and C: running time and growth
The figure compares running time trends for algorithms A, B, and C, distinguishing elapsed time from its rate of growth.
The horizontal axis is input size n, marked from 0 to 9. The vertical axis is running time, with labels 0, 5, 10, an ellipsis, and 1000000. The gap between 10 and 1000000 is compressed, so vertical distances do not use a uniform scale.
All three algorithms perform the same print operation. The table takes the print counts from the code in the text and the line colors and positions from the figure.
| Algorithm | Number of prints | Running time shown in the figure |
|---|---|---|
| A | 1 | A green horizontal line between 0 and 5 on the vertical axis |
| B | n | A rising blue line from the origin crosses A at n = 1 and approaches the vertical tick at 10 when n = 9 |
| C | 1000000 | An orange horizontal line at 1000000 on the vertical axis |
The counts for A and C are independent of n. Both are O(1), although their running times differ greatly. B grows linearly with n and is O(n). Extrapolating the print counts, B meets C at n = 1000000, beyond the horizontal range shown.
How does time complexity analysis compare with calculating running time directly?
- Time complexity is an effective measure of efficiency. For example, the running time of algorithm
Bgrows linearly. When \(n > 1\) it is slower thanA, and when \(n > 1000000\) it is slower thanC. For sufficiently large \(n\), a constant-time algorithm will outperform a linear-time algorithm. This is what a growth trend tells us. - Time complexity is easier to estimate. Neither the platform nor the type of elementary operation changes the growth trend here. We can assign each operation the same unit of time and simply count operations instead of timing them individually. This makes estimation much easier.
- Time complexity has limitations. Algorithms
AandChave the same time complexity but very different running times. Similarly, althoughBhas higher time complexity thanC, for small \(n\), algorithmBclearly outperformsC. Time complexity alone often cannot rank algorithms in cases like these. Even with these limitations, complexity analysis remains the most effective and widely used way to assess algorithm efficiency.
2.3.2 Asymptotic upper bound of a function¶
Consider the following function with input size \(n\):
Let \(T(n)\) denote the number of operations as a function of input size \(n\). For the function above, the count is:
The function \(T(n)\) is linear, so running time grows linearly and the time complexity is linear.
Linear time complexity is written \(O(n)\). This is an example of big-\(O\) notation: the \(O\) denotes an asymptotic upper bound on \(T(n)\).
Analyzing time complexity amounts to finding an asymptotic upper bound on the operation count \(T(n)\). This has a precise mathematical definition.
Asymptotic upper bound of a function
If there exist a positive real number \(c\) and a real number \(n_0\) such that \(T(n) \leq c \cdot f(n)\) for every \(n > n_0\), then \(f(n)\) is an asymptotic upper bound on \(T(n)\). We write \(T(n) = O(f(n))\).
As the figure shows, we look for a function \(f(n)\) such that, as \(n\) tends to infinity, \(T(n)\) and \(f(n)\) have the same order of growth, up to a constant factor \(c\).
Figure 2-8 Asymptotic upper bound of a function
Description of Figure 2-8: Asymptotic upper bounds beyond a threshold
Two curves illustrate the relationship that matters for an asymptotic upper bound: which curve stays above the other after a threshold.
The horizontal axis is input size n, marked from 0 to 14. The vertical axis is function value and has no numerical tick labels. The blue curve is the operation count T(n). The orange curve is c·f(n), the candidate function f(n) scaled by a positive constant c. The figure gives no specific formulas for the functions.
A dashed green vertical line marks n₀ where the curves meet between 7 and 8. From 1 to 7, the blue curve fluctuates above the orange curve. Beyond n₀, both curves continue upward, with the orange curve always above the blue one.
The condition at the bottom states that there is a positive constant c and a threshold n₀ such that T(n) ≤ c·f(n) for every n > n₀. We then write T(n) = O(f(n)) and call f(n) an asymptotic upper bound. It does not matter that T(n) exceeded c·f(n) before the threshold. The curves need not be equal everywhere.
2.3.3 Estimating time complexity¶
An asymptotic upper bound may feel abstract at first. Start with the estimation procedure. Its mathematical meaning will become clearer with practice.
By definition, once we have identified \(f(n)\), we can write the time complexity as \(O(f(n))\). How do we find the upper bound \(f(n)\)? First count the operations, then determine their asymptotic upper bound.
1. Step 1: Count the operations¶
We can go through the code line by line, from top to bottom. Since the constant \(c\) in \(c \cdot f(n)\) can be arbitrarily large, we can ignore constant factors and constant terms in the operation count \(T(n)\). This gives us a few shortcuts.
- Ignore the constant terms in \(T(n)\). They are independent of \(n\), so they do not affect time complexity.
- Drop constant factors. For example, for a loop running \(2n\) or \(5n + 1\) times, we can simplify the count to \(n\). The coefficient of \(n\) does not change the time complexity.
- Multiply counts for nested loops. The total number of operations is the product of the outer and inner loop counts. Apply shortcuts
1.and2.to each loop separately.
Let's use these shortcuts to count operations in a function:
The formulas below give the full count and the simplified count. Both yield the same time complexity, \(O(n^2)\).
2. Step 2: Determine the asymptotic upper bound¶
The highest-order term in \(T(n)\) determines the time complexity. As \(n\) tends to infinity, this term dominates and we can disregard the others.
The table gives some examples. A few coefficients are deliberately exaggerated to show that even a huge coefficient cannot change the order of growth. As \(n\) tends to infinity, those constants cease to matter.
Table 2-2 Operation counts and their time complexities
| Operation count \(T(n)\) | Time complexity \(O(f(n))\) |
|---|---|
| \(100000\) | \(O(1)\) |
| \(3n + 2\) | \(O(n)\) |
| \(2n^2 + 3n + 2\) | \(O(n^2)\) |
| \(n^3 + 10000n^2\) | \(O(n^3)\) |
| \(2^n + 10000n^{10000}\) | \(O(2^n)\) |
2.3.4 Common growth rates¶
For input size \(n\), Figure 2-9 shows common time complexities in increasing order.
Figure 2-9 Common time complexities
Description of Figure 2-9: Growth rates of five common time complexities
The chart compares how five time complexities grow with input size.
The horizontal axis is input size n, marked from 1 to 14. The vertical axis is operation count T(n), with no numerical tick labels. The curves illustrate growth trends. They do not give measured counts for a particular program or unscaled function values.
The table orders the curves from lowest to highest at their right ends, following the upward arrow labeled “Lower to higher, better to worse.”
| Complexity (lowest to highest at the right edge) | Shape in the chart |
|---|---|
| Constant O(1) | A green horizontal line. The operation count stays the same as n changes. |
| Logarithmic O(log n) | A cyan curve rises slowly, with a gradually decreasing slope. |
| Linear O(n) | A straight blue line rises at a constant slope. |
| Quadratic O(n²) | An orange curve bends upward and gets steeper. |
| Exponential O(2ⁿ) | A red curve stays near the bottom at first, then rises steeply. |
Some curves cross early on. For example, the red exponential curve starts below the blue linear and orange quadratic curves, then overtakes them. The crossings are illustrative. They do not specify exact operation counts or the input size at which one algorithm becomes more efficient than another. For sufficiently large n, a lower order means slower growth in the operation count.
1. Constant time \(O(1)\)¶
In constant time, the operation count is independent of input size \(n\). It stays the same as \(n\) changes.
In the following function, the operation count size may be large, but it is independent of the input size \(n\). The time complexity is therefore still \(O(1)\):
Visualize execution
2. Linear time \(O(n)\)¶
In linear time, the operation count grows linearly with input size \(n\). This often happens in a single loop:
Visualize execution
Traversing an array or a linked list takes \(O(n)\) time, where \(n\) is the length of the array or list:
Visualize execution
Notice that the meaning of input size \(n\) depends on the type of input. In the first example, the variable \(n\) itself gives the size. In the second, the size is the array length \(n\).
3. Quadratic time \(O(n^2)\)¶
In quadratic time, the operation count grows with the square of the input size \(n\). This often happens in nested loops. Here the outer loop runs \(O(n)\) times, as does the inner loop on each pass, giving an overall time complexity of \(O(n^2)\):
Visualize execution
The figure compares constant, linear, and quadratic time.
Figure 2-10 Constant, linear, and quadratic time complexity
Description of Figure 2-10: Loops and operation counts
The figure compares how the work grows for a single operation, one loop, and two nested loops.
Each small square represents one basic operation. A surrounding loop box marks the part that repeats.
| Structure | Number of basic operations | Time complexity |
|---|---|---|
| No loop | 1 | Constant O(1) |
| One loop with n iterations | n | Linear O(n) |
| Two nested loops, n iterations each | n×n=n² | Quadratic O(n²) |
A box inside another box indicates nesting. For every outer iteration, the inner loop runs a full n times. Multiply the counts to get n × n. Two loops run one after the other would have their counts added instead.
In bubble sort, for example, the outer loop runs \(n - 1\) times. The inner loop runs \(n-1\), \(n-2\), \(\dots\), \(2\), and \(1\) times on successive passes, averaging \(n / 2\) iterations. The time complexity is therefore \(O((n - 1) n / 2) = O(n^2)\):
def bubble_sort(nums: list[int]) -> int:
"""Quadratic time (bubble sort)"""
count = 0 # Counter
# Outer loop: the unsorted range is the closed interval [0, i]
for i in range(len(nums) - 1, 0, -1):
# Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for j in range(i):
if nums[j] > nums[j + 1]:
# Swap nums[j] and nums[j + 1]
tmp: int = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
count += 3 # Swapping two elements takes 3 elementary operations
return count
/* Quadratic time (bubble sort) */
int bubbleSort(vector<int> &nums) {
int count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
int bubbleSort(int[] nums) {
int count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (int i = nums.length - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
int BubbleSort(int[] nums) {
int count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (int i = nums.Length - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
func bubbleSort(nums []int) int {
count := 0 // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for i := len(nums) - 1; i > 0; i-- {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for j := 0; j < i; j++ {
if nums[j] > nums[j+1] {
// Swap nums[j] and nums[j + 1]
tmp := nums[j]
nums[j] = nums[j+1]
nums[j+1] = tmp
count += 3 // Swapping two elements takes 3 elementary operations
}
}
}
return count
}
/* Quadratic time (bubble sort) */
func bubbleSort(nums: inout [Int]) -> Int {
var count = 0 // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for i in nums.indices.dropFirst().reversed() {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for j in 0 ..< i {
if nums[j] > nums[j + 1] {
// Swap nums[j] and nums[j + 1]
let tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
count += 3 // Swapping two elements takes 3 elementary operations
}
}
}
return count
}
/* Quadratic time (bubble sort) */
function bubbleSort(nums) {
let count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (let i = nums.length - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
function bubbleSort(nums: number[]): number {
let count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (let i = nums.length - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
int bubbleSort(List<int> nums) {
int count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (var i = nums.length - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (var j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
fn bubble_sort(nums: &mut [i32]) -> i32 {
let mut count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for i in (1..nums.len()).rev() {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for j in 0..i {
if nums[j] > nums[j + 1] {
// Swap nums[j] and nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
count
}
/* Quadratic time (bubble sort) */
int bubbleSort(int *nums, int n) {
int count = 0; // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (int i = n - 1; i > 0; i--) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Swapping two elements takes 3 elementary operations
}
}
}
return count;
}
/* Quadratic time (bubble sort) */
fun bubbleSort(nums: IntArray): Int {
var count = 0 // Counter
// Outer loop: the unsorted range is the closed interval [0, i]
for (i in nums.size - 1 downTo 1) {
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for (j in 0..<i) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
val temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
count += 3 // Swapping two elements takes 3 elementary operations
}
}
}
return count
}
### Quadratic time (bubble sort)###
def bubble_sort(nums)
count = 0 # Counter
# Outer loop: the unsorted range is the closed interval [0, i]
for i in (nums.length - 1).downto(0)
# Inner loop: swap adjacent elements to move the largest in [0, i] to index i
for j in 0...i
if nums[j] > nums[j + 1]
# Swap nums[j] and nums[j + 1]
tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
count += 3 # Swapping two elements takes 3 elementary operations
end
end
end
count
end
Visualize execution
4. Exponential time \(O(2^n)\)¶
Cell division is a familiar example of exponential growth. Start with \(1\) cell. After one round of division there are \(2\) cells, after two rounds there are \(4\), and after \(n\) rounds there are \(2^n\).
The figure and code below simulate cell division in \(O(2^n)\) time. The input \(n\) is the number of rounds of division. The return value count is the total number of individual divisions.
/* Exponential time (iterative) */
int exponential(int n) {
int count = 0, base = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative) */
int exponential(int n) {
int count = 0, base = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative) */
int Exponential(int n) {
int count = 0, bas = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < bas; j++) {
count++;
}
bas *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative)*/
func exponential(n int) int {
count, base := 0, 1
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for i := 0; i < n; i++ {
for j := 0; j < base; j++ {
count++
}
base *= 2
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count
}
/* Exponential time (iterative) */
func exponential(n: Int) -> Int {
var count = 0
var base = 1
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for _ in 0 ..< n {
for _ in 0 ..< base {
count += 1
}
base *= 2
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count
}
/* Exponential time (iterative) */
function exponential(n) {
let count = 0,
base = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (let i = 0; i < n; i++) {
for (let j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative) */
function exponential(n: number): number {
let count = 0,
base = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (let i = 0; i < n; i++) {
for (let j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative) */
int exponential(int n) {
int count = 0, base = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (var i = 0; i < n; i++) {
for (var j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative) */
fn exponential(n: i32) -> i32 {
let mut count = 0;
let mut base = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for _ in 0..n {
for _ in 0..base {
count += 1
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
count
}
/* Exponential time (iterative) */
int exponential(int n) {
int count = 0;
int bas = 1;
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < bas; j++) {
count++;
}
bas *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential time (iterative) */
fun exponential(n: Int): Int {
var count = 0
var base = 1
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
for (i in 0..<n) {
for (j in 0..<base) {
count++
}
base *= 2
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count
}
Visualize execution
Figure 2-11 Exponential time complexity
Description of Figure 2-11: A recursion tree that branches in two at each level
The node count doubles at each successive level. To find the total work, sum the counts across levels.
Each square represents one operation. The root is level 1. The top label reads “Recursion tree: each node branches in two,” and a brace on the right reads “n levels,” where n is a positive integer.
The first three levels have 1, 2, and 4 nodes. Each nonterminal node connects to two children. Below level 3, eight arrows lead to ellipses. Eight squares separated by ellipses illustrate the last level. Its node count is not fixed at eight. The right column gives the counts as powers, and the table also gives their decimal values for the first few levels. For n ≤ 3, use only the levels that exist. Row n then coincides with the corresponding earlier row.
| Level (root at level 1) | Node count |
|---|---|
| 1 | 2⁰ = 1 |
| 2 | 2¹ = 2 |
| 3 | 2² = 4 |
| n | 2ⁿ⁻¹, or two raised to the power n−1 |
At the bottom, the counts sum to 2⁰ + 2¹ + … + 2ⁿ⁻¹ = 2ⁿ − 1, or two to the power n minus one, giving O(2ⁿ). In the cell division loop before the figure, level k represents the divisions performed by individual cells in round k. Over n rounds there are 2ⁿ − 1 divisions, leaving 2ⁿ cells. Those final cells are not drawn as another level of operations. For exp_recur(n) after the figure, each square represents one call. The argument decreases from n to 1 over n levels. Counting one per call gives the same total.
Exponential time often arises in recursive algorithms. For example, the following function branches in two at each recursive step, stopping after \(n\) levels:
Visualize execution
Exponential growth is very fast. It is common in exhaustive methods such as brute-force search and backtracking. For large inputs, exponential time is prohibitive. Such problems usually call for an approach such as dynamic programming or a greedy algorithm.
5. Logarithmic time \(O(\log n)\)¶
Logarithmic growth is the reverse side of exponential growth. Suppose the input size is \(n\) and each iteration halves what remains. The number of iterations is \(\log_2 n\), the inverse function of \(2^n\).
The figure and code below illustrate repeated halving. The time complexity is \(O(\log_2 n)\), usually written \(O(\log n)\):
Visualize execution
Figure 2-12 Logarithmic time complexity
Description of Figure 2-12: Keeping half at each step gives logarithmic growth
Each round halves the remaining length. The figure pairs each retained state with one operation at that level.
Suppose n is 2 raised to a nonnegative integer power. From left to right, the columns show the remaining array length, the array of initial length n halved at each level, and one operation per level. Dark green cells and their outline mark the retained interval. Light gray cells mark the excluded interval.
An ellipsis at the top stands for earlier halvings. The final four levels appear below it. In the right column, downward arrows connect one light green operation square per level. The brace at the far right reads “log₂ n + 1 levels.” At the bottom, the figure also gives log₂ n + 1 as its total operation count, with an arrow to O(log n).
| Remaining length | Retained range in an eight-cell array |
|---|---|
| 8 | All 8 cells |
| 4 | Rightmost 4 cells |
| 2 | Rightmost 2 cells |
| 1 | Rightmost cell |
Going from n to 1 takes log₂ n halvings. The count returned by the code with while n > 1 is exactly that number. The figure counts one more operation for the final state of length 1, so its count is one larger. For example, 8 → 4 → 2 → 1 has three halvings and four state levels. The constant difference leaves the order O(log n) unchanged. The ellipsis and four rows illustrate a general input. A small input visits only its actual levels.
Like exponential time, logarithmic time often occurs in recursive functions. The following code produces a recursion tree of height \(\log_2 n\):
Visualize execution
Logarithmic time is common in divide-and-conquer algorithms that split problems into smaller, simpler pieces. It grows slowly and is an attractive time complexity, second only to constant time among the common growth rates.
What is the base of the logarithm in \(O(\log n)\)?
More precisely, dividing the size by \(m\) at each step gives time complexity \(O(\log_m n)\). The change-of-base formula shows why using a different base gives the same time complexity:
In other words, we can change the base \(m\) without affecting complexity. We usually omit the base \(m\) and write logarithmic time as \(O(\log n)\).
6. Linearithmic time \(O(n \log n)\)¶
Linearithmic time often arises in nested loops where the two loop counts have orders \(O(\log n)\) and \(O(n)\). Here is the corresponding code:
Visualize execution
The figure shows another way linearithmic time arises. Each level of the binary tree accounts for \(n\) operations, and the tree has \(\log_2 n + 1\) levels. This gives a time complexity of \(O(n \log n)\).
Figure 2-13 Linearithmic time complexity
Description of Figure 2-13: Work per level in a divide-and-conquer tree
The number of subproblems doubles while the work per subproblem halves, keeping total work per level constant.
Suppose n is 2 raised to a nonnegative integer power. The boxes represent subproblems. Each node does as many operations as its current size. Starting at the root, each subproblem splits into two at the next level.
The right side totals the operations by level. Only four boxes separated by ellipses appear on the bottom level. They stand for all n leaves. The table lists levels for a general input size. A small n may have no intermediate levels, and the leaf level may coincide with an earlier row. The tree does not always have five levels.
| Level | Number of subproblems | Operations per subproblem | Total for this level |
|---|---|---|---|
| Root level | 1 | n | n |
| Next level | 2 | n/2 | n |
| Following level | 4 | n/4 | n |
| Intermediate levels (if any) | Keeps doubling | Keeps halving | n |
| Leaf level | n | 1 | n |
Number the root level 0. At level d, there are 2^d subproblems taking n/2^d operations each, so their product is always n. At the leaf level, each subproblem has size 1. Thus 2^d = n and d = log₂ n. From level 0 through level log₂ n there are log₂ n + 1 levels. At the bottom the work n per level is multiplied by the number of levels, giving n(log₂ n + 1) = n log₂ n + n, or O(n log n).
Widely used sorting algorithms such as quicksort, merge sort, and heapsort typically take \(O(n \log n)\) time.
7. Factorial time \(O(n!)\)¶
Factorial growth arises when we enumerate permutations. Given \(n\) distinct elements, the number of possible orderings is:
This count is usually computed recursively. In the figure and code below, there are \(n\) choices at the first level, then \(n - 1\) branches from each choice at the second, and so on. Branching stops at level \(n\):
Visualize execution
Figure 2-14 Factorial time complexity
Description of Figure 2-14: Choosing a permutation one position at a time gives factorial growth
Each time we fill another position in a permutation, one fewer element remains available. Multiplying the numbers of choices gives the total number of permutations.
The n elements are distinct. The gray root at the top represents the state before any choice. Each level in a dashed box below it fills the next position. The right-hand brace labeled “n levels” spans only the choice levels below the root, excluding the root itself.
The left column gives the number of branches from each node at the preceding level. The right column gives the total nodes on the current level. Ellipses represent intermediate levels. Small n requires only the choice levels that actually occur, so the last row may coincide with an earlier row.
| Choice level | Branches per node at the preceding level | Total nodes on this level |
|---|---|---|
| 1 | n | n |
| 2 | n−1 | n(n−1) |
| 3 | n−2 | n(n−1)(n−2) |
| Intermediate levels (if any) | Decreases by 1 per level | Continue multiplying |
| n, the final level | 1 | n! |
The formula at the bottom, n × (n−1) × … × 1 = n!, counts the green leaves on the bottom level. Each leaf represents a complete permutation and contributes one base-case count to the value returned by factorial_recur. The value n! counts leaves only. Even including the root and all intermediate levels, the tree has fewer than 3 times n! nodes. Each call contains a loop, but each loop iteration creates exactly one edge to a child call. The tree has one fewer edge than nodes, so including the loop work still gives O(n!). This counts constant work per edge and excludes the extra cost of copying complete permutations.
Since \(n! > 2^n\) for every \(n \geq 4\), factorial growth is even faster than exponential growth and is also prohibitive for large \(n\).
2.3.5 Worst-case, best-case, and average-case time complexity¶
An algorithm's time efficiency often depends on the distribution of its inputs. Suppose we are given an array nums of length \(n\). The array nums contains each number from \(1\) through \(n\) exactly once, in random order. Our task is to return the index of \(1\). Consider these cases.
- When
nums = [?, ?, ..., 1], the last element is \(1\) and we must traverse the whole array. The worst-case time complexity is \(O(n)\). - When
nums = [1, ?, ?, ...], the first element is \(1\). We can stop immediately, regardless of the array length. The best-case time complexity is \(\Omega(1)\).
Worst-case time complexity corresponds here to an asymptotic upper bound, expressed in big-\(O\) notation. Correspondingly, the best case gives an asymptotic lower bound, expressed in \(\Omega\) notation:
def random_numbers(n: int) -> list[int]:
"""Generate a shuffled array containing 1, 2, ..., n"""
# Generate nums with elements 1, 2, 3, ..., n
nums = [i for i in range(1, n + 1)]
# Shuffle the array elements at random
random.shuffle(nums)
return nums
def find_one(nums: list[int]) -> int:
"""Find the index of 1 in the array nums"""
for i in range(len(nums)):
# Best case: 1 is the first element, so the search takes O(1) time
# Worst case: 1 is the last element, so the search takes O(n) time
if nums[i] == 1:
return i
return -1
/* Generate a shuffled array containing { 1, 2, ..., n } */
vector<int> randomNumbers(int n) {
vector<int> nums(n);
// Generate the array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Use the system time as the random seed
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
// Shuffle the array elements at random
shuffle(nums.begin(), nums.end(), default_random_engine(seed));
return nums;
}
/* Find the index of 1 in the array nums */
int findOne(vector<int> &nums) {
for (int i = 0; i < nums.size(); i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] == 1)
return i;
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
int[] randomNumbers(int n) {
Integer[] nums = new Integer[n];
// Generate the array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Shuffle the array elements at random
Collections.shuffle(Arrays.asList(nums));
// Integer[] -> int[]
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nums[i];
}
return res;
}
/* Find the index of 1 in the array nums */
int findOne(int[] nums) {
for (int i = 0; i < nums.length; i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] == 1)
return i;
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
int[] RandomNumbers(int n) {
int[] nums = new int[n];
// Generate the array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Shuffle the array elements at random
for (int i = 0; i < nums.Length; i++) {
int index = new Random().Next(i, nums.Length);
(nums[i], nums[index]) = (nums[index], nums[i]);
}
return nums;
}
/* Find the index of 1 in the array nums */
int FindOne(int[] nums) {
for (int i = 0; i < nums.Length; i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] == 1)
return i;
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
func randomNumbers(n int) []int {
nums := make([]int, n)
// Generate the array nums = { 1, 2, 3, ..., n }
for i := 0; i < n; i++ {
nums[i] = i + 1
}
// Shuffle the array elements at random
rand.Shuffle(len(nums), func(i, j int) {
nums[i], nums[j] = nums[j], nums[i]
})
return nums
}
/* Find the index of 1 in the array nums */
func findOne(nums []int) int {
for i := 0; i < len(nums); i++ {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if nums[i] == 1 {
return i
}
}
return -1
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
func randomNumbers(n: Int) -> [Int] {
// Generate the array nums = { 1, 2, 3, ..., n }
var nums = Array(1 ... n)
// Shuffle the array elements at random
nums.shuffle()
return nums
}
/* Find the index of 1 in the array nums */
func findOne(nums: [Int]) -> Int {
for i in nums.indices {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if nums[i] == 1 {
return i
}
}
return -1
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
function randomNumbers(n) {
const nums = Array(n);
// Generate the array nums = { 1, 2, 3, ..., n }
for (let i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Shuffle the array elements at random
for (let i = 0; i < n; i++) {
const r = Math.floor(Math.random() * (i + 1));
const temp = nums[i];
nums[i] = nums[r];
nums[r] = temp;
}
return nums;
}
/* Find the index of 1 in the array nums */
function findOne(nums) {
for (let i = 0; i < nums.length; i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] === 1) {
return i;
}
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
function randomNumbers(n: number): number[] {
const nums = Array(n);
// Generate the array nums = { 1, 2, 3, ..., n }
for (let i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Shuffle the array elements at random
for (let i = 0; i < n; i++) {
const r = Math.floor(Math.random() * (i + 1));
const temp = nums[i];
nums[i] = nums[r];
nums[r] = temp;
}
return nums;
}
/* Find the index of 1 in the array nums */
function findOne(nums: number[]): number {
for (let i = 0; i < nums.length; i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] === 1) {
return i;
}
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
List<int> randomNumbers(int n) {
final nums = List.filled(n, 0);
// Generate the array nums = { 1, 2, 3, ..., n }
for (var i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Shuffle the array elements at random
nums.shuffle();
return nums;
}
/* Find the index of 1 in the array nums */
int findOne(List<int> nums) {
for (var i = 0; i < nums.length; i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] == 1) return i;
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
fn random_numbers(n: i32) -> Vec<i32> {
// Generate the array nums = { 1, 2, 3, ..., n }
let mut nums = (1..=n).collect::<Vec<i32>>();
// Shuffle the array elements at random
nums.shuffle(&mut thread_rng());
nums
}
/* Find the index of 1 in the array nums */
fn find_one(nums: &[i32]) -> Option<usize> {
for i in 0..nums.len() {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if nums[i] == 1 {
return Some(i);
}
}
None
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
int *randomNumbers(int n) {
// Allocate heap memory for a one-dimensional array of n elements of type int
int *nums = (int *)malloc(n * sizeof(int));
// Generate the array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Shuffle the array elements at random
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return nums;
}
/* Find the index of 1 in the array nums */
int findOne(int *nums, int n) {
for (int i = 0; i < n; i++) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] == 1)
return i;
}
return -1;
}
/* Generate a shuffled array containing { 1, 2, ..., n } */
fun randomNumbers(n: Int): Array<Int?> {
val nums = IntArray(n)
// Generate the array nums = { 1, 2, 3, ..., n }
for (i in 0..<n) {
nums[i] = i + 1
}
// Shuffle the array elements at random
nums.shuffle()
val res = arrayOfNulls<Int>(n)
for (i in 0..<n) {
res[i] = nums[i]
}
return res
}
/* Find the index of 1 in the array nums */
fun findOne(nums: Array<Int?>): Int {
for (i in nums.indices) {
// Best case: 1 is the first element, so the search takes O(1) time
// Worst case: 1 is the last element, so the search takes O(n) time
if (nums[i] == 1)
return i
}
return -1
}
### Generate a shuffled array containing 1, 2, ..., n ###
def random_numbers(n)
# Generate nums with elements 1, 2, 3, ..., n
nums = Array.new(n) { |i| i + 1 }
# Shuffle the array elements at random
nums.shuffle!
end
### Find the index of 1 in the array nums ###
def find_one(nums)
for i in 0...nums.length
# Best case: 1 is the first element, so the search takes O(1) time
# Worst case: 1 is the last element, so the search takes O(n) time
return i if nums[i] == 1
end
-1
end
Visualize execution
We rarely use best-case time complexity in practice. The best case usually has a very low probability, so it can give a misleading impression. Worst-case time complexity is more useful because it gives us a bound we can count on when choosing an algorithm.
In the example above, only particular input arrangements yield the best and worst cases. These arrangements may be unlikely, so neither case necessarily represents the algorithm's usual efficiency. Average-case time complexity describes efficiency on random inputs. Here we express it in \(\Theta\) notation.
For some algorithms, the average case under a random input distribution is easy to estimate. In the shuffled array above, \(1\) is equally likely to appear at any index. The loop therefore runs about half the array length, \(n / 2\), on average, giving an average-case time complexity of \(\Theta(n / 2) = \Theta(n)\).
For more complex algorithms, finding the average time complexity is often difficult because the overall mathematical expectation under the input distribution is hard to calculate. In such cases we usually evaluate the algorithm by its worst-case time complexity.
Why do we so rarely see \(\Theta\) notation?
Perhaps because big-\(O\) is so easy to say, we often use it when discussing average-case time complexity. Strictly speaking, this usage lacks precision. In this book and other material, read a statement such as “average time complexity \(O(n)\)” as \(\Theta(n)\) in this context.