Time and Space Complexity: Metrics for Building Scalable Algorithms

Time and Space Complexity: Metrics for Building Scalable Algorithms

Francisco

-
Follow me on
linkedin icongithub icon
Published on Dec 28, 2025

Most of the time, we do not think too much about the performance of our algorithms and code—especially in the age of AI, where part of the code is being generated by agents rather than by humans. However, when dealing with large amounts of data and non-trivial problems, it becomes critically important to ask whether a solution is robust and efficient enough, and whether what is produced by AI agents is truly optimal or merely a local solution.

Algorithmic complexity has been widely studied for decades, and any efficient algorithm or solution should consider, at a minimum, the following dimensions:

  1. Time complexity: How fast is the algorithm?
  2. Space complexity: How much computational memory is required?

Time complexity: Less is more

Time complexity is not related to the hardware level of your computer; instead, it measures the number of operations an algorithm performs until it completes its execution, and it is mainly expressed as a function of the input size.

When the input is small, there is usually no need to worry too much about time complexity. However, as the input size grows, the execution time can increase exponentially. This is known as the asymptotic behavior of algorithms.

Example

Suppose that the running time of an algorithm is given by:

f(n)=n*n+3n

Given n as the input size:

When n is small, both terms matter with similar magnitude.
However, as n grows large, the term 3n becomes much less relevant compared to n², since it grows at a lower rate.

That is why we say that, for large values of n, the behavior of this function is essentially:

f(n)≈n*n

Or, stated differently, the algorithm has a complexity of O(n · n).

Concrete idea

Let’s think for a moment about a more concrete example. Imagine you are a teacher who needs to evaluate the assignments of all your students. Your tasks are:

  • Compare each student’s assignment with the others to detect possible copying.
  • Assign the corresponding grade to each test.

This job has two parts: one with O(n) complexity and another with O(n · n) complexity.
If this were a Python function, it could be represented as follows:

1def review_tests(d: dict):
2 keys = list(d.keys())
3 values = [d[k] for k in keys]
4
5
6 dup_flags = np.zeros(len(keys), dtype=bool)
7 for i in range(len(values)):
8 for j in range(len(values)):
9 if i != j and values[i] == values[j]:
10 dup_flags[i] = True
11 break
12
13 ground_truth = "I think it's 7"
14 for k in d:
15 d[k] = 5 if d[k] == ground_truth else 0
16
17 return {
18 'array': dup_flags,
19 'note': d
20 }

This algorithm has two types of operations: comparisons and grade assignments. If we need to review each test and compare it with all the others, the number of comparisons grows approximately as n · n. Then, assigning a grade to each student adds an additional cost of n.

Therefore, the total running time is n · n + n, and its asymptotic complexity is O(n²).

With 10 students this is fast, but with 100 or 1,000 students the number of operations increases significantly (for example, with 1,000 students it is on the order of one million). In real-world scenarios, such as processing millions of transactions, a quadratic approach can become impractical, and it is worth looking for more efficient alternatives.

The theory: Relationship between complexity, number of operations, and input size

The relationship between the number of operations, the input size, and algorithmic complexity has been studied in many ways, and curves have been constructed to represent this behavior. In general terms, problems can be represented according to their algorithmic complexity using the following curves:

Gemini_Generated_Image_rnssusrnssusrnss (1) (1).png

Where:

  • O(1): Constant. Always the same cost. For example, accessing a transaction in a list of transactions.
  • O(log n): Logarithmic. Grows very slowly. For example, binary search for an element in a list.
  • O(√n): Square root. Slower than logarithmic growth.
  • O(n): Linear. Time grows proportionally. For example, iterating over a dataset once.
  • O(n log n): Linearithmic.
  • O(n²): Quadratic. Expensive and grows quickly. For example, iterating over a dataset and comparing all elements with each other.
  • O(2ⁿ): Exponential. Grows explosively and becomes almost unusable due to its high cost.
  • O(n!): Factorial. All possible permutations. For example, given a dataset, finding all possible ways to order it.

As we can see, as we aim to perform more complex tasks and work with larger volumes of data, it becomes necessary to know how to optimize our solutions—both when designing them and when building robust systems, not only in terms of data, but also in terms of computation.

Space complexity: Using less additional memory helps alleviate the problem

Space complexity measures how much additional memory an algorithm uses during its execution, as a function of the input size. This memory includes auxiliary variables, temporary data structures (such as lists, arrays, or matrices), and, in the case of recursive algorithms, the memory used by the call stack. It does not consider the memory required to store the input data itself, but only the extra memory the algorithm consumes while running.

Let’s return to the teacher example. We want to check whether students are copying while also assigning their grades. If we wanted to further optimize the solution, we could eliminate some of the additional memory created when storing and processing the data, as follows:

1def review_tests(d: dict):
2 dup_flags = np.zeros(len(d), dtype=bool)
3
4 # Detect duplicated answers (no auxiliary lists)
5 for i, (_, v1) in enumerate(d.items()):
6 for j, (_, v2) in enumerate(d.items()):
7 if i != j and v1 == v2:
8 dup_flags[i] = True
9 break
10
11 # Grading
12 ground_truth = "I think it's 7"
13 for k in d:
14 d[k] = 5 if d[k] == ground_truth else 0
15
16 return {
17 'array': dup_flags,
18 'note': d
19 }

In this case, the variables keys and values are no longer stored, reducing the algorithm’s space complexity from O(3n) to O(n). This does not mean it stops being O(n), since the variable dup_flags is still part of the solution and continues to grow linearly with the input size.

Conclusion

These concepts are often left out of traditional data science training. However, understanding them is essential, as many solutions that seem correct in small-scale environments fail in production because they do not consider fundamental principles of computing, along with good design practices and code efficiency.

Ir arriba