Skip to content
BytePatterns

O(1) and O(n)

Big-O: lesson 2 of 5

One step, or every step? That's the whole difference.

Lesson 2 of 5 · 4 min

O(1) and O(n)

Step 1 of 11

Same list, two jobs: read one slot, or look for a value that could be anywhere.

The Idea

O(1) means the work never changes, no matter how large the input gets. O(n) means you touch every item once. Telling these two apart in your own code is the fastest complexity skill to pick up.

Real-World Example

A vending machine is O(1): press B4 and the snack drops, whether the machine holds ten items or two hundred. Hunting for one brand down every supermarket aisle is O(n), so a bigger store means a longer walk.

The Code

def first_item(nums):
    # one lookup, same cost for any list size -> O(1)
    return nums[0]

def contains(nums, target):
    # may scan every element -> O(n)
    for x in nums:
        if x == target:
            return True
    return False

Your turn

Put the steps in the right order.

  1. Compare the current item to the target
  2. Start at the first element
  3. Return False after the whole scan finds nothing
  4. Move to the next element if there is no match

Mini quiz

1 / 3

Which operation is O(1)?