Formal (Mathematical) Definition
Remember that there's quite a bit of math involved in computer science! Computer science is basically a field of mathematics, so you'll probably run into a lot of mathematical theory in coding. Get used to it!
Here we give a formal mathematical definition of Big O notation.
A function is said to be if there exists positive constants and such that for all , .
In simpler terms, it signifies that the growth rate of is bounded by the growth rate of for sufficiently large , up to a constant factor.
Example (with Proof)
For example, let's say we have an algorithm that makes computations. This is an example (in pseudocode):
for each element in an array:
- check if it the number is 1. if so, print "1!"
- check if it the number is 2. if so, print "2!"
- check if it the number is 3. if so, print "3!"
Here, for each of the elements in the array, we do 3 comparisons. So we can express the function for which this algorithm's runtime grows as .
To prove that the algorithm is , we need to show that its growth rate is bounded by a linear function for sufficiently large .
Given , we want to find a function such that for some positive constant and for all greater than or equal to some .
We can choose . Then, for all , we have:
where and .
This shows that is indeed , as its growth rate is bounded above by a constant multiple of for sufficiently large .
This may seem a little complicated, especially if you aren't a math major. But after some practice, finding the runtimes of your algorithms will become easier, I promise!
General Rules
You don't need to write a long, mathematical proof every time you find the runtime of an algorithm. Here are some general rules for finding the Big O of your algorithm:
- Focus on the dominant term: When analyzing the time complexity, focus on the term with the largest growth rate as the input size increases. This dominant term determines the overall behavior of the algorithm.
becomes .
- Ignore constant factors: Ignore constant factors when expressing the time complexity using Big O notation. Constant factors do not change the overall growth rate of the algorithm.
becomes .
More Examples
-
is , because for sufficiently large , grows linearly with .
-
is , because for sufficiently large , grows quadratically with .
-
is , because for sufficiently large , the exponential term dominates the polynomial term.
-
is , because for sufficiently large , the linear term dominates the logarithmic term.
-
is , because the sine and cosine functions are bounded between -1 and 1, regardless of the value of .