Big O Notation
Introduction
Big O notation is a mathematical notation for describing the complexity of an algorithm. Time and space complexity are two things we care about when it comes to designing algorithms.
Worst Case
is the best case complexity of an algorithm. is the average case complexity of an algorithm. is the worst case complexity of an algorithm.
O(n)
The time complexity of the following code is .
Drop Constant
The constant can be dropped from the expression. For example, can be rewritten as .
O(n^2)
The time complexity of the following code is .
The following code runs for time.
(and so on) can be simplified to .
Drop non-dominants
The time complexity of the following code is .
We can drop the non-dominant term n, therefore the time complexity is .
O(1)
means the time complexity is constant, i.e., no matter how large the input size is, the time complexity is always the same.
O(log n)
Binary search is an example of an algorithm that has time complexity of .
Different Terms for Inputs
The above function has two parameters, a and b, and the time complexity is . It can not be simplified to or .
Lists
: my_list.append(item), my_list.pop(), my_list.lookup(index)
: my_list.pop(n), my_list.insert(n, item), my_list.remove(item), my_list.lookup(item) (because the list needs to be reindexed)
Wrap up
Last updated