Time and Space Complexity

Explore the fundamentals of time and space complexity and learn how to analyze them through code examples.

🎯 Introduction

Understanding time and space complexity and how to calculate them helps you analyze and optimize frontend performance, improving execution efficiency and resource usage. Code examples show how different algorithms and code structures affect complexity, giving you a foundation for writing efficient frontend programs.


⏰ What Is Time Complexity?

Time complexity describes how an algorithm's running time grows as the input size increases.

Consider an everyday example:

Buying one apple at a supermarket takes little time. Buying a basket of fruit takes longer. Time complexity helps estimate how the time required grows with the number of items.

Common Big O notations include O(1), O(n), O(n²), and O(log n). The following examples illustrate them.

🐢 Example 1: O(1) — Constant Time

function printFirstElement(arr) {
    console.log(arr[0]);
}

Regardless of the array's size, this code accesses one element. The work is constant, so its time complexity is O(1).

🐇 Example 2: O(n) — Linear Time

function printAllElements(arr) {
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
}

The loop visits every array element. Each additional element adds one iteration, giving O(n) time complexity.

🐢🐢 Example 3: O(n²) — Quadratic Time

function printPairs(arr) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length; j++) {
            console.log(arr[i], arr[j]);
        }
    }
}

These nested loops each run n times. The total number of iterations is n * n, giving O(n²) time complexity.

function binarySearch(arr, target) {
    let left = 0,
        right = arr.length - 1;

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

Each iteration halves the search range. The number of iterations grows logarithmically with the input size, giving O(log n) time complexity.


💾 What Is Space Complexity?

Here, space complexity describes the extra memory an algorithm needs during execution, excluding the input itself.

For an analogy:

Writing a single sentence in a letter uses little paper; writing more requires more paper. Paper represents space in this example, just as space complexity measures how memory usage grows.

Space complexity also uses Big O notation, such as O(1), O(n), O(n²), and O(log n). Consider the following examples.

📦 Example 1: O(1) Space

function sumTwoNumbers(a, b) {
    return a + b;
}

Only two fixed variables are used. Memory usage does not grow with the input, so the space complexity is O(1).

📦 Example 2: O(n) Space

function createArray(n) {
    let arr = [];
    for (let i = 0; i < n; i++) {
        arr.push(i);
    }
    return arr;
}

As n grows, so does the new array. Extra memory is proportional to the input size, giving O(n) space complexity.

📦 Example 3: O(n) Space for Recursive Calls

function factorial(n) {
    if (n === 1) return 1;
    return n * factorial(n - 1);
}

Each recursive call takes space on the call stack. Space complexity is proportional to recursion depth, which is O(n) here.


🛠 How Do You Analyze Complexity?

Focus on the most time-consuming operations or the structures that use the most memory.

Consider another everyday scenario:

Searching across a table for your keys resembles O(n); checking one fixed spot resembles O(1).

When calculating complexity, we usually ignore constant factors and lower-order terms. For example, O(2n) simplifies to O(n), since constant factors do not change the growth rate.

❓ Questions and Answers

Q1: Why doesn't time complexity use units of time?

Time complexity describes growth rather than actual duration, which varies with hardware and runtime conditions. Big O notation provides a more general measure.

Q2: Does recursion always lead to high space complexity?

No. Tail-call optimization can reduce memory usage, although ordinary recursion can require more space as the call stack grows.


🎉 You have learned time complexity, space complexity, and basic algorithm analysis!