Short answer: time complexity describes how the number of basic steps an algorithm takes grows as its input size n grows. It is a growth rate, not a time in seconds, and it is usually written in Big O notation. O(n) means the steps grow in proportion to n. O(n²) means doubling n makes the work about four times bigger.
Below you will find a step-by-step method to calculate time complexity, then six common classes from O(1) to O(2ⁿ). Each class has a short program that counts its own steps. Every output shown was produced by running the code.
What is time complexity?
Time complexity measures how much work an algorithm does as a function of its input size, called n. n might be the number of items in an array, the characters in a string or the nodes in a graph.
Work is counted in basic steps: anything that takes a fixed amount of time whatever the input size. Comparing two numbers, adding them, reading a[i] and assigning a variable are basic steps.
Why not time the program in seconds? Because seconds depend on the machine, the language and the compiler. MIT's algorithms course compares algorithms by "asymptotic performance relative to problem input size, in order to ignore constant factor differences in hardware performance" (MIT 6.006, Recitation 1). Asymptotic means "as n gets very large".
So time complexity answers one question: if the input gets 10 times bigger, how much more work is there? Big O notation names the answer:
- O(1), constant: the work does not grow with n.
- O(log n), logarithmic: the work grows by a fixed amount each time n doubles.
- O(n), linear: 10 times the input, 10 times the work.
- O(n log n), linearithmic: a little more than linear. Good sorting algorithms are here.
- O(n²), quadratic: 10 times the input, 100 times the work.
- O(2ⁿ), exponential: one more item doubles the work.
Here log n means log to base 2 (log₂ n). Inside Big O the base does not matter, because changing it only multiplies the result by a constant.
How to calculate time complexity, step by step
- Decide what n is. Usually it is the size of the main input. If there are two independent inputs, name them n and m.
- Count how many times each block runs. A loop from 0 to n runs n times.
- Sequential blocks add. A loop of n runs followed by one of n² runs gives n + n².
- Nested loops multiply. An n-step loop inside another n-step loop runs its body n × n = n² times.
- A loop that halves (or doubles) its variable runs about log₂ n times. Halving 1,024 reaches 1 after 10 steps, because 2¹⁰ = 1,024.
- Keep the fastest-growing term and drop constant factors. 3n² + 5n + 2 becomes O(n²). For large n, the n² term is almost all of the work.
- For recursion, write a recurrence and solve it. A recurrence gives the cost T(n) in terms of the cost of smaller inputs.
Worked example
This function has three blocks: a loop, a nested loop and a halving loop. It counts every pass.
def count_steps(n):
steps = 0
for i in range(n): # Block A: one loop over n items
steps += 1
for i in range(n): # Block B: a loop inside a loop
for j in range(n):
steps += 1
k = n
while k > 1: # Block C: halve k until it reaches 1
k = k // 2
steps += 1
return steps
for n in [10, 100, 1000]:
total = count_steps(n)
share = 100 * n * n / total
print(f"n = {n:>4}: {total:>9,} steps, n^2 = {n * n:>9,} ({share:.1f}% of all steps)")
n = 10: 113 steps, n^2 = 100 (88.5% of all steps)
n = 100: 10,106 steps, n^2 = 10,000 (99.0% of all steps)
n = 1000: 1,001,009 steps, n^2 = 1,000,000 (99.9% of all steps)
- Block A runs n times.
- Block B runs n × n = n² times, because the loops are nested.
- Block C runs ⌊log₂ n⌋ times (rounded down): 3 times for n = 10, 6 for n = 100 and 9 for n = 1,000.
- The blocks run one after another, so the counts add: n² + n + ⌊log₂ n⌋. For n = 10 that is 100 + 10 + 3 = 113, as printed.
Drop everything except the fastest-growing term and the answer is O(n²). The output shows why that is safe: at n = 1,000 the n² term is already 99.9% of all the steps.
Recursion: from recurrence to complexity
The cost of a recursive call is its own work plus the cost of the calls it makes. These three recurrences cover most interview questions, and each has a program later in this post.
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n) = T(n/2) + 1 | O(log n) |
| Merge sort | T(n) = 2T(n/2) + n | O(n log n) |
| Naive recursive Fibonacci | T(n) = T(n − 1) + T(n − 2) + 1 | Θ(φⁿ), where φ ≈ 1.618 |
To solve one, draw the recursion tree (a diagram of every call) and add up the work on each level. The Master Theorem is a ready-made formula for recurrences of the form T(n) = aT(n/b) + f(n), like the first two rows.
Time complexity examples: six classes you will meet most
Each program counts its own steps for a few values of n, so you can watch the growth. Compile the C ones with cc file.c && ./a.out and run the Python ones with python3 file.py.
O(1): constant time
An algorithm is O(1) when its step count does not depend on n. Reading a[i], pushing onto a stack and checking if a number is even are O(1).
This C program adds 1 + 2 + … + n with the formula n(n + 1)/2. That is one multiply, one add and one divide for any n, counted as one step.
#include <stdio.h>
long long operations = 0;
/* Sum of 1 + 2 + ... + n using the formula n(n + 1) / 2 */
long long sum_formula(long long n) {
operations++; /* one multiply, one add, one divide: counted as 1 step */
return n * (n + 1) / 2;
}
int main(void) {
long long sizes[] = {10, 1000, 1000000};
for (int i = 0; i < 3; i++) {
operations = 0;
long long s = sum_formula(sizes[i]);
printf("n = %7lld sum = %12lld steps = %lld\n", sizes[i], s, operations);
}
return 0;
}
n = 10 sum = 55 steps = 1
n = 1000 sum = 500500 steps = 1
n = 1000000 sum = 500000500000 steps = 1
The count stays at 1 from n = 10 to n = 1,000,000. O(1) does not mean "one line of code". Fifty statements are still O(1) if none of them depends on n.
O(log n): logarithmic time
An algorithm is O(log n) when each step throws away a fixed fraction of the input, usually half. Binary search is the classic case. It checks the middle item of a sorted array, discards the half that cannot hold the target, and repeats.
The program searches for every value from −1 to 2n in sorted arrays of 32, 1,024 and 32,768 items, so some targets are present and some are missing. It reports the largest number of probes (items looked at) any search needed.
#include <stdio.h>
#include <stdlib.h>
/* Returns how many array items binary search looks at (probes) */
int binary_search_probes(const int *a, int n, int target) {
int low = 0, high = n - 1, probes = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
probes++;
if (a[mid] == target) return probes;
if (a[mid] < target) low = mid + 1;
else high = mid - 1;
}
return probes; /* target not found */
}
int main(void) {
int sizes[] = {32, 1024, 32768};
for (int s = 0; s < 3; s++) {
int n = sizes[s];
int *a = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) a[i] = 2 * i; /* sorted even numbers */
int worst = 0; /* try every value, present or missing */
for (int t = -1; t <= 2 * n; t++) {
int p = binary_search_probes(a, n, t);
if (p > worst) worst = p;
}
int halvings = 0; /* how many times n can be halved to reach 1 */
for (int k = n; k > 1; k /= 2) halvings++;
printf("n = %5d halvings = %2d worst case = %2d probes\n", n, halvings, worst);
free(a);
}
return 0;
}
n = 32 halvings = 5 worst case = 6 probes
n = 1024 halvings = 10 worst case = 11 probes
n = 32768 halvings = 15 worst case = 16 probes
After k halvings, about n/2ᵏ items are left. One item is left when n/2ᵏ = 1, so k = log₂ n. That is 5 halvings for 32 items, 10 for 1,024 and 15 for 32,768. The search then needs one last probe to check that final item. So the worst case is ⌊log₂ n⌋ + 1 probes: 6, 11 and 16.
The input grew 1,024 times, but the worst case grew by only 10 probes. Each doubling of n adds one probe. Binary search needs sorted data, and our binary search guide covers its code and common bugs.
O(n): linear time
An algorithm is O(n) when it does a fixed amount of work per input item. Finding the largest number in an unsorted array and linear search are O(n). Here is the same sum, done with a loop.
#include <stdio.h>
long long operations = 0;
/* Sum of 1 + 2 + ... + n by adding one number at a time */
long long sum_loop(long long n) {
long long total = 0;
for (long long i = 1; i <= n; i++) {
total += i;
operations++; /* one addition per loop pass */
}
return total;
}
int main(void) {
long long sizes[] = {10, 1000, 1000000};
for (int i = 0; i < 3; i++) {
operations = 0;
long long s = sum_loop(sizes[i]);
printf("n = %7lld sum = %12lld steps = %lld\n", sizes[i], s, operations);
}
return 0;
}
n = 10 sum = 55 steps = 10
n = 1000 sum = 500500 steps = 1000
n = 1000000 sum = 500000500000 steps = 1000000
Same answers as the formula, but 1,000,000 steps instead of 1 for n = 1,000,000. Two correct programs can have very different time complexities, which is why you analyse them.
O(n log n): linearithmic time
An algorithm is O(n log n) when it does O(n) work on each of about log n levels. Merge sort is the standard example. It splits the list in half, sorts each half recursively, then merges the sorted halves in one pass. The program counts writes, each time an item is placed into a merged list.
writes = 0 # how many times an item is copied into place during merging
def merge_sort(items):
global writes
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
writes += 1
for rest in (left[i:], right[j:]):
merged.extend(rest)
writes += len(rest)
return merged
for n in [8, 1024, 65536]:
writes = 0
data = list(range(n, 0, -1)) # n numbers in reverse order
assert merge_sort(data) == sorted(data)
levels = n.bit_length() - 1 # log2(n) for these powers of two
print(f"n = {n:>6,}: {writes:>9,} writes = {n:,} x {levels} levels")
n = 8: 24 writes = 8 x 3 levels
n = 1,024: 10,240 writes = 1,024 x 10 levels
n = 65,536: 1,048,576 writes = 65,536 x 16 levels
The count is exactly n × log₂ n for these sizes. Splitting 65,536 items in half repeatedly takes 16 levels, and each level merges all 65,536 items once. That is T(n) = 2T(n/2) + n. Merge sort does this on every input, so it is Θ(n log n) in the best, average and worst case. The price is O(n) extra memory. See merge sort explained for a full walkthrough.
O(n²): quadratic time
An algorithm is O(n²) when it does O(n) work for each of n items, usually with a loop inside a loop. This C program checks for a duplicate by comparing every pair. Its arrays have no duplicates, so it never stops early, which is its worst case.
#include <stdio.h>
#include <stdlib.h>
long long comparisons = 0;
/* Does the array contain the same value twice? Check every pair. */
int has_duplicate(const int *a, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
comparisons++;
if (a[i] == a[j]) return 1;
}
}
return 0;
}
int main(void) {
int sizes[] = {10, 100, 1000, 2000};
for (int s = 0; s < 4; s++) {
int n = sizes[s];
int *a = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) a[i] = i; /* no duplicates: worst case */
comparisons = 0;
int found = has_duplicate(a, n);
printf("n = %4d duplicate = %d comparisons = %7lld\n", n, found, comparisons);
free(a);
}
return 0;
}
n = 10 duplicate = 0 comparisons = 45
n = 100 duplicate = 0 comparisons = 4950
n = 1000 duplicate = 0 comparisons = 499500
n = 2000 duplicate = 0 comparisons = 1999000
The inner loop starts at i + 1, so it runs n − 1 times, then n − 2, and so on down to 0. The total is n(n − 1)/2: 45 for n = 10 and 499,500 for n = 1,000. That is n²/2 − n/2, which is O(n²) once you drop the constant and the lower-order term.
Doubling n from 1,000 to 2,000 made the work about 4 times bigger (499,500 to 1,999,000). That ×4 on doubling is the fingerprint of quadratic time.
If the inner loop runs over a different list of m items, the count is n × m. Write that as O(n·m). It is only O(n²) when m grows like n. The faster fix for this problem is a hash set of items seen so far: O(n) on average, because a set lookup is O(1) on average in CPython (Python docs).
O(2ⁿ): exponential time
An algorithm is exponential when one more input item multiplies the work by a constant factor. For O(2ⁿ), it doubles. Going through every subset of n items takes at least 2ⁿ steps, because there are exactly 2ⁿ subsets.
The classic interview example is naive recursive Fibonacci. Each call with n ≥ 2 makes two more calls, for n − 1 and n − 2. The tree shows every call made by fib(4).

fib(2) is computed twice and fib(1) three times. The program counts every call for n = 10, 20 and 30. It compares plain recursion with a memoised version, which stores each answer the first time it is computed.
calls = 0
def fib(n): # plain recursion
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
def fib_memo(n, memo): # same recursion, but remembers answers
global calls
calls += 1
if n < 2:
return n
if n not in memo:
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
for n in [10, 20, 30]:
calls = 0
value = fib(n)
plain_calls = calls
calls = 0
fib_memo(n, {})
print(f"fib({n}) = {value:>7,}: plain {plain_calls:>9,} calls, memoised {calls:>2} calls")
fib(10) = 55: plain 177 calls, memoised 19 calls
fib(20) = 6,765: plain 21,891 calls, memoised 39 calls
fib(30) = 832,040: plain 2,692,537 calls, memoised 59 calls
- The plain version explodes. From n = 20 to n = 30 the calls grew about 123 times, from 21,891 to 2,692,537.
- O(2ⁿ) is true but loose. True doubling would multiply the calls by 2¹⁰ = 1,024 over 10 steps, not 123. The exact count is 2 × fib(n + 1) − 1, for example 177 = 2 × 89 − 1. fib(n) grows like φⁿ, where φ ≈ 1.618 is the golden ratio, and φ¹⁰ ≈ 123. So the tight bound is Θ(φⁿ). O(2ⁿ) is a correct upper bound, just not a tight one.
- Memoisation makes it linear. The memoised version makes 2n − 1 calls, so it is O(n). Storing answers to sub-problems like this is the core of dynamic programming.
Exponential algorithms only suit small n. The Competitive Programmer's Handbook suggests O(2ⁿ) fits a 1-second limit for n up to about 20. O(n!), factorial time, grows even faster. Trying every ordering of n items takes at least n! steps.
Time complexity growth table
Rough step counts for each class, with log n as log₂ n and constant factors ignored. A script computed every cell.
| Class | n = 10 | n = 100 | n = 1,000 | n = 10⁶ | Rough time at n = 10⁶ (rule of thumb) |
|---|---|---|---|---|---|
| O(1) | 1 | 1 | 1 | 1 | Under a microsecond |
| O(log n) | 3.3 | 6.6 | 10.0 | 19.9 | Under a microsecond |
| O(n) | 10 | 100 | 1,000 | 1,000,000 | About 0.01 s |
| O(n log n) | 33 | 664 | 9,966 | 19,931,569 | About 0.2 s |
| O(n²) | 100 | 10,000 | 1,000,000 | 1,000,000,000,000 | About 10,000 s (about 2.8 hours) |
| O(2ⁿ) | 1,024 | about 1.3 × 10³⁰ | about 1.1 × 10³⁰¹ | a 301,030-digit number | Never finishes in practice |
The last column is an estimate, not a measurement. It uses a common competitive-programming rule of thumb of about 10⁸ simple steps per second. The Competitive Programmer's Handbook says "a modern computer can perform some hundreds of millions of operations in a second". Real speed depends on the language, the machine and the cost of each step. The gap between rows is the point: at n = 10⁶, O(n log n) fits a 1-second limit and O(n²) is nowhere close.

From slowest-growing to fastest: O(1) < O(log n) < O(√n) < O(n) < O(n log n) < O(n²) < O(n³) < O(2ⁿ) < O(n!).
Big O vs Big Omega vs Big Theta
These three notations are bounds on a function, such as a step count. They are not the same thing as the worst, best and average case. Mixing the two up is the most common mistake in this topic. The definitions below follow MIT 6.006, Recitation 1, for non-negative functions f(n) and g(n).
- Big O, upper bound. f(n) is O(g(n)) if some c > 0 and integer n₀ > 0 give f(n) ≤ c · g(n) for all n ≥ n₀. From some point on, f grows no faster than g, up to a constant factor.
- Big Omega (Ω), lower bound. f(n) is Ω(g(n)) if some c > 0 and integer n₀ > 0 give c · g(n) ≤ f(n) for all n ≥ n₀. f grows at least as fast as g.
- Big Theta (Θ), tight bound. f(n) is Θ(g(n)) if it is both O(g(n)) and Ω(g(n)). f grows like g, up to constant factors.
An example with numbers: take f(n) = 3n² + 5n + 2. With c = 4 and n₀ = 6, f(n) ≤ 4n² for every n ≥ 6 (at n = 6, f(6) = 140 and 4 × 36 = 144). So f(n) is O(n²). Also 3n² ≤ f(n) for every n ≥ 1, so f(n) is Ω(n²). Both hold, so f(n) is Θ(n²).
Bounds are not cases
A case picks which inputs you look at: the slowest input of size n (worst case) or the fastest (best case). A bound describes how a function grows. Any bound can describe any case. Insertion sort shows the difference. It slides each item left past every larger item before it. The program counts comparisons on sorted and reverse-sorted input.
def insertion_sort_comparisons(items):
a = list(items)
comparisons = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] <= key:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
assert a == sorted(items)
return comparisons
for n in [10, 100, 1000]:
best = insertion_sort_comparisons(range(n)) # already sorted
worst = insertion_sort_comparisons(range(n, 0, -1)) # reverse sorted
print(f"n = {n:>4}: sorted input {best:>3} comparisons, reversed input {worst:>7,} comparisons")
n = 10: sorted input 9 comparisons, reversed input 45 comparisons
n = 100: sorted input 99 comparisons, reversed input 4,950 comparisons
n = 1000: sorted input 999 comparisons, reversed input 499,500 comparisons
Sorted input takes n − 1 comparisons and reversed input takes n(n − 1)/2. So the precise statements are:
- The worst-case running time of insertion sort is Θ(n²).
- Its best-case running time is Θ(n).
- Over all inputs, its running time is O(n²) and Ω(n).
- "Insertion sort is Θ(n²)" with no case named is wrong, because on sorted input it is linear.
"Big O means worst case" is a habit, not a definition. People usually quote the worst case, and usually in Big O. But "the best case of insertion sort is O(n)" is also a correct statement.
Time complexity of sorting algorithms: which is best?
n is the number of items, k the range of values, d the number of digits and b the base. Extra space is memory beyond the input array.
| Algorithm | Best | Average | Worst | Extra space |
|---|---|---|---|---|
| Bubble sort (with early exit) | O(n) | O(n²) | O(n²) | O(1) |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) stack on average |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) |
| Radix sort (LSD) | O(d·(n + b)) | O(d·(n + b)) | O(d·(n + b)) | O(n + b) |
Which sorting algorithm has the best time complexity? The honest answer has two parts.
For comparison sorts, O(n log n) in the worst case is the best possible. A comparison sort learns the order only by asking "is a smaller than b?". All the sorts above except counting and radix work this way. n items have n! possible orderings, and each comparison has two outcomes. So any comparison sort needs at least log₂(n!) comparisons in its worst case, and log₂(n!) grows as n log n (MIT 6.006, Lecture 5). For n = 1,000 the minimum is 8,530 comparisons. Merge sort and heap sort match this bound in the worst case, up to a constant factor. Quick sort matches it on average.
Non-comparison sorts can be linear, under conditions. Counting sort uses each value as an array index, so it takes O(n + k) time. That is O(n) when the range k is O(n). Radix sort runs a counting sort per digit, so it is also linear when keys have a bounded number of digits. Both need integer-like keys.
In everyday code, use your language's built-in sort. Python's list.sort() is O(n log n) (Python docs). For code and traces of each algorithm, read our sorting algorithms guide.
Space complexity in one minute
Space complexity is how much extra memory an algorithm needs as n grows, in the same Big O notation. Usually you count only memory beyond the input, called auxiliary space.
- The loop sum and binary search use a few variables: O(1) extra space.
- Merge sort builds merged lists: O(n) extra space.
- Each active recursive call sits on the call stack. Naive Fibonacci goes up to n calls deep, so it uses O(n) stack space while making Θ(φⁿ) calls.
Common mistakes when finding time complexity
- Calling every nested loop O(n²). An inner loop of fixed length, such as 26 letters, is O(1), so the total stays O(n).
- Missing hidden loops. In Python,
x in my_listandmy_list.pop(0)are both O(n) (Python docs). Run either one n times on an n-item list and you get O(n²). - Saying "Big O is the worst case". Big O is an upper bound. The worst case is a choice of input.
- Assuming hash lookups are always O(1). They are O(1) on average, but O(n) in the worst case, when every key hashes to the same value.
Common time complexity interview questions
- Complexity of
for (i = 1; i < n; i *= 2)? O(log n), because i doubles each pass. - Complexity of a loop
for j in range(i)nested insidefor i in range(n)? O(n²). The inner body runs 0 + 1 + … + (n − 1) = n(n − 1)/2 times. - Binary search? O(log n) in the worst case, since each probe halves the search space. O(1) in the best case.
- Why does quick sort have an O(n²) worst case? If the pivot is always the smallest or largest item, each split removes one item. That is n levels of O(n) work.
FAQ
What is time complexity in simple words?
Time complexity tells you how the work an algorithm does grows as its input gets bigger. It counts basic steps, not seconds, so the answer is the same on any computer. It is written in Big O notation. O(n) means the work grows in step with the input, and O(n²) means doubling the input makes it about four times bigger.
How do you calculate the time complexity of an algorithm?
Count how many times each block of code runs in terms of the input size n. Add the counts of blocks that run one after another. Multiply the counts of nested loops. A loop that halves its variable runs about log n times. For recursion, write a recurrence. Finally, keep only the fastest-growing term and drop constant factors.
Which time complexity is the best?
O(1) is the best, because the work does not grow with the input at all. Next come O(log n), O(n) and O(n log n). But each problem has a minimum you cannot beat. For example, any comparison sort needs Ω(n log n) comparisons in the worst case, so O(n log n) is the best possible for comparison sorting.
Is Big O the worst case and Big Omega the best case?
No. Big O is an upper bound and Big Omega is a lower bound on a function. Worst case and best case are choices of input, and any bound can describe any case. For example, insertion sort's worst case is Θ(n²) and its best case is Θ(n). The confusion comes from people usually quoting the worst case in Big O.
What is the time complexity of a program in C?
The same rules apply in every language. A single loop from 0 to n is O(n). Two nested loops over n are O(n²). A loop that doubles or halves its counter is O(log n). The language only changes constant factors, which Big O ignores. The C examples in this post count their steps, so you can check each rule yourself.
Keep going
Practise reading complexities on real algorithms in our sorting algorithms guide. Then read what DSA is and why companies test it to see where time complexity fits in interviews.
If you want to build these skills on real backend and full-stack projects, with mentors reviewing your code, look at Crio's Software Development Fellowship Program.