Time & Space Complexity

Welcome to the Time and Space Complexity section of JDCodebase! Understanding time and space trade-offs is essential for writing efficient algorithms. It helps in analyzing how your code performs as input grows.

What You’ll Learn

  • What Big O notation means
  • Common time complexities: O(1), O(log n), O(n), O(n²)
  • Best, average, and worst-case scenarios
  • How to estimate time based on loops, recursion, and input size
  • Space complexity and auxiliary space vs input space

Big O Cheat Sheet

O(1) — Constant Time: Takes the same amount of time regardless of input size.
Before: arr = [10, 20, 30]
Code: arr[0]
After: 10
O(n) — Linear Time: Time grows linearly with input size.
Before: arr = [1, 2, 3]
Code: for (let i of arr) console.log(i);
After: 1
2
3
O(n²) — Quadratic Time: Nested loops over the same input.
Before: arr = [1, 2, 3]
Code: for (let i of arr) {
    for (let j of arr) {
      console.log(i + j);
    }
  }
After: All pairwise sums
O(log n) — Logarithmic Time: Reduces the problem size each step (e.g., binary search).
Before: arr = [1, 2, 3, 4, 5, 6, 7]
Code: Binary search on sorted array
After: Found or not found in log steps
O(n log n): Divide and conquer algorithms like Merge Sort, Quick Sort (average case).
Before: [5, 2, 3, 1, 4]
Code: arr.sort() // uses O(n log n) internally
After: [1, 2, 3, 4, 5]

Try This Example

Analyze the time and space complexity of this function.

function sumArray(arr) {
    let sum = 0;            // O(1)
    for (let i = 0; i < arr.length; i++) {
      sum += arr[i];        // O(n)
    }
    return sum;             // O(1)
  }

Input: [1, 2, 3, 4]

Expected Output: 10 (Time: O(n), Space: O(1))