Time/Space Complexity
Algorithms → functions from inputs to work
Definition 0.3. An algorithm that terminates in time on
all inputs of size has running time .
If is a set of functions, we say
has time complexity in (write or
) iff . Similarly for space complexity:
is the memory used on inputs of size .
Worst-case vs. average-case complexity. Most textbooks (and this course)
focus on worst-case: over all inputs of size . Average
case replaces the max with the expected value over some distribution.
Size measure matters. "Size" of the input is a choice. For a number, is
the number itself. For a list of length , the size is . For a graph with
vertices and edges, the size is usually . There is no canonical
choice — the analysis must say which.
Examples:
- Array lookup: — constant. Lookup doesn't depend on array size.
- Linear search: — linear. Worst case: target not present.
- Matrix multiply (naive): — cubic.
- Subsets of an -set: — exponential.
Time vs. space. You can often trade one for the other. Hash tables use
more memory but enable lookup. Quicksort uses stack space
but worst-case time.