Skip to content

Getting to Grips with Big O Notation

Posted on:February 18, 2024 at 05:22 PM

Let’s Talk About Big O Notation

📢 Note: This article kicks off a deep dive into algorithms and data structures. Keep an eye out for more insights and examples as we explore Big O and beyond! If you’re keen to learn more, check out The Last Algorithms Course You’ll Need on Frontend Masters. For the rest of this series, see the first post: Working Through an Algorithms Course

Table of Contents

Open Table of Contents

Introduction

Understanding Big O notation is key to grasping how algorithms perform. It’s a way to measure and compare the efficiency of algorithms, predicting how they’ll handle larger inputs. Big O focuses on how algorithms scale with input size, looking at both space (memory usage) and time (execution time) complexities. Knowing these complexities helps you choose the right algorithm for the job, especially when dealing with large datasets where performance matters.

Breaking Down Big O Notation

Big O notation is written as O(f(n)), where n is the size of the input, and f(n) describes how the algorithm’s run time or space requirements grow. Here’s a rundown of the most common Big O notations:

In Big O notation, we ignore constants and lower-order terms. So O(2n) is considered O(n), and O(3n²) is considered O(n²). This is because we’re interested in how the algorithm scales with large inputs, not the exact run time.

Feeling a bit overwhelmed? Don’t worry, examples are on the way!

Imagine you’re manufacturing widgets:

You can see why aiming for O(1) is preferable over O(n), which is better than O(n²). Even reducing from O(n²) to O(n log n) can make a big difference with large inputs. If you’re dealing with O(2ⁿ) or O(n!), it’s time to rethink your approach.

Big O Examples

  1. O(1) - Constant Time Complexity
    • Accessing an element in an array by index
    • Retrieving a value from a hash map by key
  2. O(log n) - Logarithmic Time Complexity
    • Binary search in a sorted array
    • Searching in a balanced binary search tree
  3. O(n) - Linear Time Complexity
    • Iterating over all elements in an array
    • Finding the minimum or maximum value in an unsorted list
  4. O(n log n) - Linearithmic Time Complexity
    • Sorting algorithms like mergesort or quicksort
    • Certain divide and conquer algorithms
  5. O(n²) - Quadratic Time Complexity
    • Nested loops over the same dataset
    • Simple sorting algorithms like bubble sort or selection sort

We’ll dive into detailed implementations and analyses of these examples, along with others, in upcoming posts.