O(n³) — cubic complexity

← O(n³) — cubic complexity

Ashterix

docs: English JsonRpcBundle docs, REST and MCP Bundle sections, package cards

en/articles/from-tg/series/algorithm-complexity/o-n3.md new file +36 −0

1 + # O(n³) — cubic complexity
2 +
3 + Things are getting really serious now. Algorithms with O(n³) use three nested loops. This means that as the data grows, the execution time grows cubically.
4 +
5 + ## Example: multiplying two matrices
6 +
7 + ```php
8 + function matrixMultiplication($matrixA, $matrixB) {
9 + $rowsA = count($matrixA);
10 + $colsA = count($matrixA[0]);
11 + $colsB = count($matrixB[0]);
12 +
13 + $result = [];
14 + for ($i = 0; $i < $rowsA; $i++) {
15 + for ($j = 0; $j < $colsB; $j++) {
16 + $result[$i][$j] = 0;
17 + for ($k = 0; $k < $colsA; $k++) {
18 + $result[$i][$j] += $matrixA[$i][$k] * $matrixB[$k][$j];
19 + }
20 + }
21 + }
22 + return $result;
23 + }
24 + ```
25 +
26 + Sounds academic, but it happens more often than you'd think: in calculations, graph building, searching for combinations. Anything that needs to compare triples of data or three-dimensional structures is a candidate for O(n³).
27 +
28 + :::warning
29 + This is a critical point already. If you can avoid code like this — avoid it. You can often find ways to bring it down to O(n²) or even O(n log n).
30 + :::
31 +
32 + ← [Previous: O(n²) — quadratic complexity](/articles/from-tg/series/algorithm-complexity/o-n2) · [Whole series](/articles/from-tg/series/algorithm-complexity) · [Next: O(2ⁿ) — exponential complexity →](/articles/from-tg/series/algorithm-complexity/o-2n)
33 +
34 + ---
35 +
36 + *First published in Ukrainian in the Telegram channel [“Created to die”](https://t.me/php_while_true/45) on June 25, 2025.*