WeCodeAcademy

Thinking About Speed: Big O

An algorithm is a step-by-step method for solving a problem. A data structure is a way of storing data so an algorithm can work with it well. The two go together: the right structure often turns a slow method into a fast one.

To compare methods we ask how the work grows as the input grows. This is called Big O notation.

Big ONameExample
O(1)constantread items[0]
O(log n)logarithmicbinary search
O(n)linearlook at every item once
O(n log n)linearithmicgood sorting
O(n squared)quadraticcompare every pair

We count steps, not seconds, so the answer does not depend on how fast your computer is. The example counts the steps of two ways of finding a duplicate.

Examplepython
Open in editor »
Quick check

A method takes twice as many steps when the input doubles. What is its Big O?

Your turn: write the code

Count how many comparisons the nested loop makes for a list of 10 items (each pair once) and print the count.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.