Skip to main content

Big O Notation

What is Big O Notation?โ€‹

Simplified analysis of an algorithm's efficiency in worst case scenario (very large input size).

Formulaโ€‹

O(n)
  • O: represents the function or algorithm that is being evaluated... "Big O"
  • n: represents the number of elements/input

Big O: Order of Complexityโ€‹

NotationNameshortDescription
๐ŸคฉO(1)Constantspeed isn't determined by input sizeAlways takes the same amount of time regardless of input size
๐Ÿ˜O(log n)Logarithmic10x data means 2x more timeAmount of work is divided by 2 after every loop iteration (binary search)
๐Ÿ™‚O(n)Linear10x more data means 10x more timeHow long it takes to run is directly based on how big N is (for loops)
๐Ÿ˜’O(nยทlog(n))Log-linear or Linearithmic10x more data means about 20x more timenested loop where the inner loop runs in log n time. (quicksort, mergesort & heapsort)
๐Ÿ˜ฌO(n^2)Quadratic10x more data means 100x more timeyou have a loop that for each element then loops over every element in nested loop
๐Ÿ˜ณO(2^n)Exponential

General Rulesโ€‹

  1. Certain terms dominate others, drop lower order terms
O(1) < O(log n) < O(n) < O(nยทlog(n)) < O(n2) < O(2n) < O(n!)
  1. Ignore constants
5n -> n -> O(n)

Examplesโ€‹

T(n) = 17n4 + 3n3 + 4n + 8
1. O(n4) dominates over O(n3) O(n) O(1)
T(n) = 17n4
2. Ignore constants
T(n) = O(n4)

Constant Runtime | O(1) | O of 1โ€‹

As the input size increases, the number of operations that we perform never changes.

// Big O Notation: O(1)
function log(array) {
console.log(array[0]);
console.log(array[1]);
}

Logarithmic Runtime | O(log n) | O of log nโ€‹

With every operation performed we cut the input in half.

// Big O Notation: O(log n)
function binarySearch(array, key) {
var low = 0;
var high = array.length - 1;
var mid;
var element;

while (low <= high) {
mid = Math.floor((low + high) / 2, 10);
element = array[mid];
if (element < key) {
low = mid + 1;
} else if (element > key) {
high = mid - 1;
} else {
return mid;
}
return -1;
}
}

Linear Runtime | O(n) | O of nโ€‹

  • The runtime is proportional to the input size.
  • As the input increases so does the runtime.
  • Each time we add to input we add to how many times we need to execute the function.
// Big O Notation: O(n)
function logAll(array) {
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
}

Quadratic Runtime | O(n^2) | O of n squaredโ€‹

  • Iterates through the entire array and for every element it goes through the entire array again.
// Big O Notation: O(n^2)
function addAndLog(array) {
for (var i = 0; i < array.length; i++) {
for (var j = o; j < array.length; j++) {
console.log(array[i] + array[j]);
}
}
}

Exponential Runtime | O(2^n) | O of 2 raised to the n-th powerโ€‹

  • Runtime grows exponentially based on input size.
// Big O Notation: O(2^n)
function fibonacci(num) {
if (num <= 1) return 1;

return fibonacci(num - 1) + fibonacci(num - 2);
}