Why Does Big O Notation / Time Complexity Matter?
Why Does Big O Notation / Time Complexity Matter?
adsd
1) Also referred to as Time Complexity
2) Big O Notation gives us a precise, numeric, &objective way of judging the
performance of our code.
Example Problem
Write a function that calculates the sum of all numbers from 1 up to (and including)
some number n.
// naive solution
function addUpToNaive(n) {
var total = 0; // accumulator
for (var i = 1; i <= n; i++) {
Big O Notation:
adsd
total += i; // loop over
}
return total;
}
Counting Operations
Big O Notation:-
It’s about counting no. of operations to perform for how large N is.
Big O Notation:
adsd
//////////////////////////////////////////////////////////////////
Big O Notation:
adsd
Big O only cares about worst case scenarios & general trends as N
approaches infinity
Quadratic: f(n) = n^2 As input grows by n, the runtime grows at n squared. So it gets
really big, really fast. Not the best solution.
Big O Notation:
adsd
Rules of thumb to simplify Big O Expressions
As inputs scale to infinity, the constants and smaller terms don't matter.
1. Constants don't matter. O(500) -> O(1), O(2n) -> O(n), O(13n^2) -> O(n^2)
2. Smaller terms don't matter. O(n + 10) -> O(n) , O(1000n + 50) -> O(n) , O(n^2 +
5n + 8) -> O(n^2)
Time complexity: How can we analyze the runtime of an algorithm runs as the size of
the inputs increase.
Space complexity
We can also use Big O notation to analyze space complexity.
function sum(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++){
total += arr[i];
}
return total;
}
Big O Notation:
adsd
O(1) space Our total number of space is two: i and total. Total is only counted once, even
though its updated.
The input amount doesn't matter, since we are looking at space taken up in the
algorithm. We aren't creating new variables based on the length.
//////////////////////////////////////////////
function double(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(2 * arr[i]);
}
return newArr;
}
O(n)
Rules of Thumb
3. Reference types (arrays or objects) are generally O(n), where n is the length (for
arrays) or number of keys (for objects).
Log2(8) = 3 Can be read as: Two to what power equals 8? Or 2^x = 8 -> 2^3 = 8
Log2(16) = 4
RECAP
1. We use Big O Notation to analyze the performance of an algorithm
Big O Notation:
adsd
2. Big O Notation gives a high level understanding of time or space complexity of
an algorithm.
3. Big O notation doesn't care about precision, only about general trends: linear,
quadratic, constant