AlgoViz

O(n²) quadratic time

easy 14 min

O(n²) means the work grows with the square of the input, usually because a loop runs inside another loop over the same data.

Where it shows up

The same pattern appears across everyday software.

  • Collision detection in games

    A naive physics step tests every pair of objects for overlap, n(n-1)/2 tests per frame. With 1,000 objects that is about half a million checks 60 times a second, so engines first bucket objects into a spatial grid or tree and only test neighbours.

  • Removing duplicate records

    Comparing each row of a spreadsheet or database export with every other row is quadratic and stalls on a few hundred thousand rows. Hashing a normalised key per row (an email, an ID) finds duplicates in one pass.

  • Similarity and recommendation

    Computing the similarity of every user to every other user, or every document to every other document, fills an n × n matrix. At millions of items this is infeasible, which is why systems use approximate nearest-neighbour indexes instead.

  • Sorting small arrays inside fast sorts

    Python's Timsort and many quicksort implementations switch to insertion sort for short runs of a few dozen items. It is O(n²), but on tiny inputs its simple loop beats the overhead of divide and conquer.

  • Comparing two sequences

    Diff tools and DNA alignment compare every position of one sequence with every position of the other using dynamic programming, O(n · m) time. Two files of 10,000 lines each mean 100 million cells, which is why diff tools add heuristics.