O(n) — linear complexity

← O(n) — linear complexity

Ashterix

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

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

1 + # O(n) — linear complexity
2 +
3 + This is the most common type of complexity, the one you see every day.
4 +
5 + Imagine you have an array of 1000 elements and need to find one value. If the array isn't sorted, there is simply no other way than checking every element. And that's exactly what O(n) means — the execution time grows in direct proportion to the number of elements.
6 +
7 + ## Example: linear search in an array
8 +
9 + ```php
10 + function linearSearch($array, $target) {
11 + for ($i = 0; $i < count($array); $i++) {
12 + if ($array[$i] === $target) {
13 + return $i;
14 + }
15 + }
16 + return -1;
17 + }
18 + ```
19 +
20 + A classic. From `foreach` to `array_map` or `array_filter` — most of your iterations run in O(n).
21 +
22 + O(n) isn't bad yet. It's normal. But if you process millions of records, you need to think about how to do better.
23 +
24 + ← [Previous: O(1) — constant complexity](/articles/from-tg/series/algorithm-complexity/o-1) · [Whole series](/articles/from-tg/series/algorithm-complexity) · [Next: O(log n) — logarithmic complexity →](/articles/from-tg/series/algorithm-complexity/o-log-n)
25 +
26 + ---
27 +
28 + *First published in Ukrainian in the Telegram channel [“Created to die”](https://t.me/php_while_true/24) on June 21, 2025.*