Time and Space Complexity
🎯 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.
🦅 Example 4: O(log n) — Logarithmic Time (Binary Search)
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).
❓ 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!
What Are Data Structures and Algorithms?
Learn the fundamentals of data structures and algorithms, why they matter, and how to use them in JavaScript.
Data Structures
Explore common frontend data structures with JavaScript examples covering the fundamentals and implementations of arrays, linked lists, stacks, queues, hash tables, trees, and graphs.
