Quadratic
Quadratic time appears when you loop over the input and, for each item, loop over the input again. The work is proportional to n times n, written O(n²).
function pairs(values) {
const result = [];
for (const a of values) {
for (const b of values) {
result.push([a, b]);
}
}
return result;
}
An input of 10 produces 100 pairs. An input of 1,000 produces 1,000,000. That growth is why nested loops over large collections deserve attention, and why a hash map can sometimes replace the inner loop.
Not every nested loop is quadratic. If the inner loop always runs a fixed number of times, the runtime stays linear.
References and further reading
- Wikipedia: Quadratic growthThe growth curve behind O(n squared).
- Big O Cheat SheetCompare common runtimes.