Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Choosing a Structure

โญ beginnerโณ 12 min read๐Ÿ“ Lesson 75 of 225

Complexity classes in plain language, and a decision table you can carry.

The vocabulary

  • O(1): cost independent of size โ€” one arithmetic step
  • O(log n): halving each step โ€” binary search
  • O(n): one pass over the data โ€” summing an array
  • O(n log n): good sorting
  • O(nยฒ): every element against every element โ€” naive sorting

Numbers make it real: for n = 1,000,000, an O(n) scan is a million steps; O(nยฒ) is a trillion. Same hardware, different worlds.

Reading a loop's complexity

for (i = 0; i < n; i++)          // O(n)
for (i = 0; i < n; i++)          // O(n) โ€” doubling i reaches n in log n steps
    i *= 2;
for (i = 0; i < n; i++)          // O(nยฒ) โ€” outer n times, inner n times
    for (j = 0; j < n; j++)

Nested loops multiply; sequential loops take the larger.

The beginner decision table

| need | reach for | |------|-----------| | a list you index often | dynamic array | | frequent inserts at the front | linked list | | undo / matching brackets / DFS | stack | | fair waiting lines, buffering | queue | | fastest lookup by key | (hash table โ€” later courses) |

Measurement beats theory

When unsure, time it. C gives you clock(); even a crude before/after print beats guessing. Theory picks the top 2 candidates; the stopwatch closes the case.