Why is standard attention O(n²) in sequence length, and what specifically is the n²?
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
The n² is the size of the attention score matrix QKᵀ: every query key pair gets one entry. Both compute and memory scale quadratically with sequence length.
Imagine a roomful of people where everyone has to shake hands with everyone else and remember each handshake. With 10 people you get 100 handshakes; with 100 people you get 10,000. The work grows with the square of the headcount, not the headcount itself. Attention does the same thing, every token has to look at every other token, so the bookkeeping for a length-n sequence is shaped like an n by n grid. That n by n grid is the n² you keep hearing about.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
5 min: where the n² lives inside QKᵀ, the difference between compute and memory complexity, the production escape-hatch hierarchy (FlashAttention, PagedAttention, ring attention, sparse patterns), and the parameter count confound to avoid.
| Approach | Compute | Memory | Exact? |
|---|---|---|---|
| Standard attention | O(n²·d) | O(n²) | Yes |
| FlashAttention | O(n²·d) | O(n) | Yes |
| Sliding window (w) | O(n·w·d) | O(n·w) | Within window only |
| Linear attention | O(n·d²) | O(n·d) | No (kernel approx) |
| Mamba / SSM | O(n·d²) | O(n·d) | No (recurrence) |
Real products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Confusing the n² compute cost with the parameter count. Attention has O(d²) parameters per layer (the projection matrices), independent of sequence length. The n² is purely about the sequence-axis interaction.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.