awesome-everything RU
↑ Back to the climb

Algorithms from zero

Thinking & complexity: code reading

Crux Read real code snippets, count the steps, derive the Big-O for time and space, predict behaviour, and spot the complexity or correctness bug.
Your altitude — climbing toward senior
ZeroJuniorMiddleSenior
You are at middle altitude — in the sky
◷ 14 min

Analysis only sticks when you do it on real code. Read each snippet, count the loops and the memory, and decide its complexity — the exact move you make when reviewing a pull request or sizing up a solution.

Goal

Practise the loop you run on any unfamiliar function: find the dominant work, multiply nested loops, separate time from space, and notice when the trouble is not speed at all but a correctness bug.

Snippet 1 — what does the nesting cost?

function countCloserPairs(points, threshold) {
  let count = 0;
  for (let i = 0; i < points.length; i++) {
    for (let j = i + 1; j < points.length; j++) {
      if (Math.abs(points[i] - points[j]) < threshold) {
        count++;
      }
    }
  }
  return count;
}
Quiz

What are the time and space complexities of countCloserPairs on n points?

Snippet 2 — predict the comparison count

function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}
// arr = [0, 1, 2, ..., 999]  (1000 sorted elements)
Quiz

For arr = [0..999], which statement about linearSearch is correct?

Snippet 3 — same output, different cost

// Version A
function sumToNLoop(n) {
  let sum = 0;
  for (let i = 1; i <= n; i++) sum += i;
  return sum;
}

// Version B
function sumToNFormula(n) {
  return n * (n + 1) / 2;
}
Quiz

Both functions return the same value. How do their complexities compare?

Snippet 4 — the bug a test might miss

function average(numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
  }
  return sum / numbers.length;
}
Quiz

The complexity is fine — O(n) time, O(1) space. But what edge case breaks correctness, and why does that matter here?

Recap

Reading complexity off code is a fixed routine: find the dominant work and keep only that term; multiply nested loops and add sequential phases; count memory structures, not loop iterations, for space; and remember a closed form can replace an O(n) loop with O(1). Then check the other axis — an algorithm with perfect Big-O can still be wrong on the edge case (empty input, division by zero) that your tests never touched.

Continue the climb ↑Thinking & complexity: predict then measure
shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.