SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

Basic algorithms: Big-O and the three O(n²) sorts

Why code that runs in 1 second on staging takes 3 hours in production: reading Big-O by intuition, the doubling test, the 10⁸-operations-per-second estimate, the three O(n²) sorts, and how to review the complexity of AI-written code.

17 Nov 20267 min readJunior

–

1. The problem

A job reconciling 10,000 transactions against 10,000 bank statement lines takes 1 second on staging. Production has 1 million on each side: 100× the data, but the job runs about 3 hours, 10,000× longer. The code isn't wrong; it just has two nested loops.

2. Key idea

Big-O is asking "how much harder does the kitchen work with more guests", not "how long does one dish take". It drops constants and keeps the fastest-growing term: 3n + 5 is O(n), n² + 100n is O(n²).

Big-O n = 10³ n = 10⁶ At 10⁸ ops/s
O(log n) ~10 ~20 instant
O(n) 10³ 10⁶ 0.01 s
O(n log n) ~10⁴ ~2·10⁷ 0.2 s
O(n²) 10⁶ 10¹² about 3 hours

2.1 Three questions before writing

  1. What is the real n in production, and in a year?
  2. Which loop runs inside which? Including hidden loops: list.contains, indexOf, removeAll are all O(n).
  3. Can the inner question be answered faster: HashSet/HashMap in O(1), or sort and scan?
Approach Use when Don't use when
Estimating with Big-O choosing an approach, n of 10⁴ and up n is always under 100: constants and cache decide
The doubling test you suspect a job slows down with data you only have one measurement

2.2 What do the O(n²) sorts still teach?

  • Insertion sort: best case O(n) when nearly sorted, stable; the JDK still uses it for small ranges inside Arrays.sort.
  • Selection sort: fewest swaps but not stable.
  • Amortized: ArrayList.add is O(1) on average despite occasional resizes. When asked about "space complexity", say you mean auxiliary space (extra memory, excluding input).

3. In Java

The most common O(n²) fix: build a HashMap before the loop, turning n × n into n + n.

JAVA
// O(n·m): for each transaction, rescan every statement line
for (Txn t : txns)
    for (BankLine b : lines)
        if (b.ref().equals(t.ref())) match(t, b);
 
// O(n + m): build the map once, each lookup O(1)
Map<String, BankLine> byRef = new HashMap<>(lines.size() * 2);
for (BankLine b : lines) byRef.put(b.ref(), b);
for (Txn t : txns) {
    BankLine b = byRef.get(t.ref());
    if (b != null) match(t, b);
}
// 1 million each: ~10¹² ops become ~2·10⁶; 3 hours become under a second

Other languages: Go map[string]BankLine, C# Dictionary, Node.js Map; in SQL, index the join column.

4. Working with AI

Give the AI: turning nested loops into HashMap/HashSet, generating 10⁵–10⁶-element test data, JMH benchmarks at n and 2n.

Check in AI-written code:

  • No List contains, indexOf or remove(Object) inside a loop over the same data.
  • Each nested loop notes its maximum n; the product stays under 10⁸.
  • No database queries or HTTP calls inside loops (N+1).
  • At least one test or benchmark runs at production data size.

5. Exercises

Exercise 1: An AI-written selection sort

The AI wrote this, described as "selection sort, stable, tested with [5, 4, 3, 2, 1]". That test passes.

JAVA
static void sortFewWrites(int[] a) {
    for (int i = 0; i < a.length - 1; i++) {
        int min = i;
        for (int j = i + 1; j < a.length; j++)
            if (a[j] < a[i]) min = j;
        int tmp = a[i]; a[i] = a[min]; a[min] = tmp;
    }
}

Find the bug, name a test that proves it, fix it.

Solution to Exercise 1
  • Main bug: it compares with a[i] instead of a[min], so min is the last position smaller than a[i], not the smallest. [5, 4, 3, 2, 1] happens to work; [3, 1, 2] gives [2, 1, 3].
  • Test: 1,000 random arrays compared against a copy run through Arrays.sort; plus the [3, 1, 2] case.
  • Fix: if (a[j] < a[min]) min = j;.
  • Bug in the description: selection sort isn't stable ([2a, 2b, 1] becomes [1, 2b, 2a]). If stability matters, use insertion sort.

Exercise 2: Diagnosing from numbers

A nightly report job: 100,000 rows take 12 s, 200,000 take 48 s, this week 400,000 take 190 s and time out at 180 s. One core at 100% CPU. The profiler shows 90% of time in ArrayList.indexOf within ReportService.dedupe. Diagnose, the 15-minute action, the root fix.

Solution to Exercise 2
  • Diagnosis: data doubles, time quadruples (12 → 48 → 190): O(n²). dedupe calls indexOf on an ArrayList inside a loop.
  • 15 minutes: raise the timeout or split the job by day to get through tonight; note that 800,000 rows would take about 13 minutes.
  • Root fix: a LinkedHashSet (dedupes, keeps order); the whole loop becomes O(n). Add a 400,000-row benchmark to CI.

Summary

  • Sequential loops add, nested loops multiply, halving is O(log n).
  • Estimate: real n × Big-O ÷ 10⁸ ops/s.
  • Data doubles, time quadruples: O(n²).
  • Fix nested loops with a prebuilt HashMap, or sort and scan.
  • Real code calls Arrays.sort/List.sort, not a hand-written O(n²) sort.

Read more: Data structures.

Practice interview questions on this topic

All Collections & DSA questions →

Loading comments…