Time Complexity
Time complexity describes how the work an algorithm does grows as its input grows. It is written with big-O notation, which reports the growth rate of that work and deliberately ignores constant factors.
Detailed Explanation
Timing a program with a stopwatch tells you about one machine, one compiler, one set of flags, and one input. That is useful but it does not answer the question you usually care about: if the input doubles, what happens to the running time? Time complexity answers that, and the answer stays true when you change machines.
The method is to count operations as a function of the input size, usually called n. Pick a representative operation — a comparison, an array access, a loop body — and count how many times it runs. A linear scan over n elements does at most n comparisons. A loop nested inside a loop over the same array does n * (n - 1) / 2 comparisons if the inner loop starts after the outer index, which is roughly n^2 / 2.
Then you throw away detail on purpose. Big-O is an upper bound: saying a routine is O(n^2) means that past some input size its cost grows no faster than a constant times n^2. Two companions exist and are worth knowing for interviews. Omega is a lower bound, and Theta is both bounds at once, so Theta(n) is the tight statement "this really is linear". Strictly speaking a linear algorithm is also O(n^2), because an upper bound does not have to be tight. Most people write O when they mean Theta, which is sloppy but universal.
Dropping constants and lower-order terms is legitimate because the highest-order term wins eventually. At n = 10000, the 3n^2 part of 3n^2 + 500n + 9000 is 300 million while everything else adds up to about 5 million. The shape of the curve is set by n^2.
That same abstraction can mislead you in C specifically, and you should know where. The model assumes every operation costs the same, and real hardware does not work that way. Walking a linked list and walking an array are both O(n), yet the array version is often several times faster because consecutive elements share cache lines and the prefetcher can see the pattern. Constant factors also decide small cases: a good O(n log n) sort loses to insertion sort's O(n^2) for twenty elements, which is exactly why production sorts switch to insertion sort on small partitions. Complexity tells you how something scales. Measurement tells you how fast it is today. You need both.
| Class | Name | Steps at n = 1000 | Steps at n = 1000000 |
|---|---|---|---|
O(1) | constant | 1 | 1 |
O(log n) | logarithmic | about 10 | about 20 |
O(n) | linear | 1000 | 1000000 |
O(n log n) | linearithmic | about 10000 | about 20000000 |
O(n^2) | quadratic | 1000000 | 1000000000000 |
O(2^n) | exponential | hopeless past n = 40 | hopeless |
Three cases get reported separately when they differ. Best case is the lucky input, average case assumes a distribution of inputs, and worst case is the guarantee. Quicksort is Theta(n log n) on average but Theta(n^2) when pivot choice goes badly. A hash table lookup is O(1) on average and O(n) when every key lands in one bucket. Worst case is the number you quote when something must not stall.
Amortized cost is a fourth idea and it is not the same as average case. A dynamic array that doubles its capacity copies n elements on the push that triggers a resize, so that single push is O(n). But doubling means the copies over n pushes total 1 + 2 + 4 + ... + n, which is under 2n, so each push costs O(1) amortized. The guarantee is about the total over a sequence of operations, not about any one call — and if you have a latency deadline, that one slow push can still miss it.
Code Examples
#include <stdio.h>
#include <stddef.h>
/* These return a step count instead of a result, so the growth rate is
something you can print rather than something you have to trust. */
static size_t linear_search_steps(const int *a, size_t n, int key)
{
size_t steps = 0;
for (size_t i = 0; i < n; i++) {
steps++;
if (a[i] == key) {
break;
}
}
return steps;
}
static size_t binary_search_steps(const int *a, size_t n, int key)
{
size_t steps = 0;
size_t lo = 0, hi = n; /* half-open range [lo, hi) */
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2; /* overflow-safe midpoint */
steps++;
if (a[mid] == key) {
break;
}
if (a[mid] < key) {
lo = mid + 1;
} else {
hi = mid; /* hi stays unsigned-safe: never mid - 1 */
}
}
return steps;
}
int main(void)
{
enum { N = 4096 };
static int a[N]; /* static: 16 KB is a lot for a stack frame */
for (size_t i = 0; i < (size_t)N; i++) {
a[i] = (int)i * 2; /* sorted, which binary search requires */
}
int key = a[N - 1]; /* the last element: worst case for both */
printf("n=%d linear: %zu binary: %zu\n",
N,
linear_search_steps(a, (size_t)N, key),
binary_search_steps(a, (size_t)N, key));
/* prints: n=4096 linear: 4096 binary: 12
4096 versus log2(4096) = 12. Double n and linear doubles; binary adds 1. */
return 0;
}#include <stdio.h>
#include <stdlib.h>
/* A growable array, to show where "O(1) amortized" comes from. */
typedef struct {
int *data;
size_t len;
size_t cap;
} IntVec;
/* Returns 1 on success, 0 if the allocation failed. */
static int vec_push(IntVec *v, int value)
{
if (v->len == v->cap) {
/* Doubling is the whole trick. Growing by a fixed +1 each time would
make n pushes cost O(n^2) copies instead of O(n). */
size_t new_cap = (v->cap == 0) ? 4 : v->cap * 2;
int *grown = realloc(v->data, new_cap * sizeof *grown);
if (grown == NULL) {
return 0; /* v->data is untouched and still valid */
}
v->data = grown;
v->cap = new_cap;
}
v->data[v->len++] = value;
return 1;
}
int main(void)
{
IntVec v = { NULL, 0, 0 };
size_t grow_steps = 0;
for (int i = 0; i < 100000; i++) {
size_t cap_before = v.cap;
if (!vec_push(&v, i)) {
fprintf(stderr, "out of memory\n");
free(v.data); /* the failure path frees too */
return EXIT_FAILURE;
}
if (v.cap != cap_before) {
grow_steps++;
}
}
printf("%zu pushes, %zu reallocations\n", v.len, grow_steps);
/* prints: 100000 pushes, 16 reallocations
Sixteen copy operations spread over 100000 pushes. Any single push can
still be slow; the average is constant. */
free(v.data); /* one free for the one live allocation */
return 0;
}Common Gotchas
`O` is an upper bound, `Theta` is the tight one
claiming a linear function is `O(n^2)` is technically correct and says almost nothing. When you mean "this is exactly linear", the honest notation is `Theta(n)`.
Constant factors and memory layout are invisible in big-O
two `O(n)` traversals can differ by 5x in wall clock because one is cache-friendly and the other chases pointers. Use complexity to pick an algorithm, then profile to pick an implementation.
Amortized is not a per-call promise
`O(1)` amortized push still means one specific push copies the whole array. In an interrupt handler or a real-time loop, reserve capacity up front instead.
Asymptotics only apply for large n
if `n` is always under 50, the algorithm with the worse growth rate and the smaller constant frequently wins. Say what range of `n` you are optimizing for before you argue about complexity.