MEPX
Chapter 3 of 12All chapters

Chapter 3 of 12

Constant and linear time

O(1) and O(n), the two you meet most.

Constant time

O(1) means the work does not depend on the input size. Reading an array by index, pushing onto a stack and looking up a hash map key are all constant on average.

  • Constant does not mean fast, it means unchanging as n grows.
  • A hash lookup is O(1) average and O(n) in the worst case with heavy collisions.

Linear time

O(n) means one pass. Summing a list, finding a maximum and searching an unsorted array are all linear, and you cannot do better when every item must be looked at.