Big O Notation: Made Easy (republished)


republished from my Medium post.

Big O Notation is like a way to measure how “hard” or “easy” a task is for an algorithm. It helps you understand how much time or memory an algorithm will need when it works with different amounts of data.

Below are a few examples with JavaScript code!


1. O(1) — Constant Time

This is the fastest! It means the process takes the same amount of time, no matter how much data you pass to it.

Example:

function firstItem(array) {
// Always looks at the first item
return array[0];
}

No matter if the array has 10 items or 1,000, this will always be super quick because it only looks at one thing.


2. O(n) — Linear Time

This means the process takes more time as you give it more data. If you have 10 items, it will take 10 steps. If you have 100 items, it will take 100 steps.

Example:

function printAllItems(array) {
// Goes through every item
array.forEach(item => console.log(item));
}

If there are 5 items, it will print 5 times. If there are 1,000 items, it will print 1,000 times. The time grows with the size of the array.


3. O(n²) — Quadratic Time

This one grows really fast because the process has to look at every item and compare it to every other item. This happens with nested loops (a loop inside another loop).

Example:


function findDuplicates(array) {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) {
console.log('Duplicate found:', array[i]);
}
}
}
}



//the function was re-written for clarity and to test
function findDuplicates(array) {
let hasDuplicates = false

for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) {
console.log('Duplicate found:', array[i])
hasDuplicates = true
}
}
}

if (!hasDuplicates) {
console.log('No duplicates found!')
}
}

// Test the function
findDuplicates(array)

Why Do We Care About Big O Notation?

Imagine you’re playing a game, and one level takes forever to load because it uses a slow algorithm. Big O helps us pick the best way to solve problems so that processes are faster and smoother.


Summary of Big O Notation:

  • O(1): Super fast! Always takes the same time.
  • O(n): Takes longer as you add more stuff.
  • O(n²): Gets slow really quickly as you add more stuff.

Now, when you write code, you can think about how your algorithm grows. Is it fast and simple like O(1), or does it take longer as the input grows like O(n) or O(n²)? Always aim to make your code more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *