Created by Kapil Sachdeva / @ksachdeva
Rate of growth of time of an algorithm with respect to the input
Why 'O' ?, Why not 'X' ?
O = Order of function
function sum(a, b) {
return a + b;
}
Unit of work here is 2
Time taken will always be constant irrespective of input
function total(list) {
let total = 0;
for(let i = 0; i < list.length; i++) {
total = total + list[i];
}
return total;
}
Time taken depends on size of input
function totalStopIf6(list) {
let total = 0;
for(let i = 0; i < list.length; i++) {
if (list[i] === 6) {
break;
}
total = total + list[i];
}
return total;
}
What is the growth of rate here ?
Always is about the worst case
Think if 6 was at the last index
Always is about the worst case
Ignore the constants
function MinMax1(list) {
const n = list.length;
let min = 0;
let max = 1000;
for(let i=0; i< n; i++) {
if (list[i] < min) min = list[i];
if (list[i] > max) max = list[i];
}
}
function MinMax2(list) {
const n = list.length;
let min = 0;
let max = 1000;
for(let i=0; i< n; i++) {
if (list[i] < min) min = list[i];
}
for(let i=0;i< n; i++) {
if (list[i] > max) max = list[i];
}
}
What is the growth of rate here ? n and 2n respectively ?
We will still say both of them are O(n)
function nestedLoop(list) {
const n = list.length;
for(let i=0; i< n; i++) {
for(let j=0; j< n; j++) {
console.log(i*j);
}
}
}
What is the growth of rate here ?
O(\(n^2)\)
function nestedLoop(list1, list2) {
const a = list1.length;
const b = list2.lenght;
for(let i=0; i< a; i++) {
for(let j=0; j< b; j++) {
console.log(i*j);
}
}
}
What is the growth of rate here ?
O(a*b)
function nestedLoop(list1, list2) {
const n = list.length;
for(let i=0; i< n; i++) {
console.log(i+1);
}
for(let i=0; i< n; i++) {
for(let j=0; j< n; j++) {
console.log(i*j);
}
}
}
What is the growth of rate here ? O(n + \(n^2)\) ?
O(\(n^2)\)
Drop the non-dominant terms
(\(2^4)\) = 2 * 2 * 2 * 2 = 16
Lograthims are opposite of exponentiation ..
We can ask ourselves, given
(\(2^x)\) = 16
What is the value of 'x' ?
(\(log_2 16)\) = x
Divide and Conquer methods still have an increase in growth rate but is not linear
Phone book is a good example
We will discuss this more when we will do Binary Search
| Description | O |
|---|---|
| Constant | O(1) |
| Logarithmic | O(log n) |
| Linear | O(n) |
| n log n | nO(log n) |
| quadratic | O(\(n^2)\) |
| polynomial | O(\(n^k)\) where k >= 1 |
| exponential | O(\(a^n)\) where a > 1 |
An array of size n will have space complexity of O(n)
A 2D array will have - O(\(n^2)\)
function sum(n) {
if (n <= 0) {
return 0;
}
return n + sum(n-1);
}
What is the growth of rate here ?
O(n) and O(n)