🔥 0
0
Lesson 3 of 10 15 min +100 XP

Time & Space Complexity

Understanding complexity analysis is essential for writing efficient code. It helps you predict how your algorithm will perform as data grows.

What is Big O Notation?

Big O notation describes the upper bound of an algorithm's growth rate. It tells us how the running time or space requirements grow as the input size increases.

Key principle: We care about the worst case and how it scales, not the exact number of operations.

Common Time Complexities

O(1) - Constant Time

The operation takes the same time regardless of input size.

// Array access by index
function getFirst(arr) {
  return arr[0];  // Always 1 operation
}

O(log n) - Logarithmic Time

The problem size is halved with each step. Very efficient!

// Binary search
function binarySearch(arr, target) {
  let left = 0, right = arr.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}

O(n) - Linear Time

Time grows proportionally with input size.

// Find maximum value
function findMax(arr) {
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) max = arr[i];
  }
  return max;
}

O(n²) - Quadratic Time

Nested iterations - gets slow quickly!

// Check for duplicates (naive)
function hasDuplicate(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) return true;
    }
  }
  return false;
}

Complexity Comparison Table

Input SizeO(1)O(log n)O(n)O(n log n)O(n²)
10131033100
1001710066410,000
1,0001101,0009,9661,000,000
10,00011310,000132,877100,000,000

Space Complexity

Space complexity measures memory usage as input grows.

ComplexityDescriptionExample
O(1)Fixed memorySwapping two variables
O(n)Linear memoryCreating a copy of an array
O(n²)Quadratic memory2D matrix of size n×n

Rules for Calculating Big O

  • Drop constants: O(2n) → O(n)
  • Drop lower terms: O(n² + n) → O(n²)
  • Consider worst case: Array search might find element first or last
  • Different inputs = different variables: O(n + m), not O(2n)

Quick Reference

OperationArrayLinked ListHash Table
AccessO(1)O(n)O(1)
SearchO(n)O(n)O(1)
InsertO(n)O(1)O(1)
DeleteO(n)O(1)O(1)

What's Next?

Now that you understand complexity, let's dive into specific data structures starting with Arrays - the most fundamental data structure.

🧠 Quick Quiz

Test your understanding of this lesson.

1

What does O(1) time complexity mean?

2

Which has better time complexity for searching a sorted array?

3

What is the time complexity of nested loops iterating over n elements?

4

Why do we use Big O notation?

Why DSA Matters