Mr. Latte


Lesson 1 of 14

Data Structures and Operation Costs

A page of names can serve as a contact list. Sorting it by name makes searching easier, but now each new name needs a place in that order. How you store data affects which operations are efficient.

Three ideas to separate

How much work does it take?

Let n be the input size. We look at how the amount of work grows as n increases. Big O describes an upper bound on that growth, not an exact duration in seconds.

Always identify the operation and the case being considered. A sequential search can finish after one comparison if the first item matches. If the match is last or missing, it examines n items.

Recursion makes a problem smaller

Recursion means a function calls itself. This function counts down through positive integers.

def countdown(n):
    if n <= 0:
        return
    print(n)
    countdown(n - 1)

countdown(3)

It prints 3, 2, and 1. The condition n <= 0 tells it when to stop, and n - 1 reduces the problem. Missing either can prevent the calls from ending.

This example takes O(n) time and O(n) call space to remember where execution must return. Python limits recursion depth, so a loop may suit large inputs better.

Check your understanding

You search 1,000 unsorted contacts from the beginning. How many items must you check if the name is missing? What happens to the worst-case work when the input doubles?

Show explanation

You inspect all 1,000 items. Doubling the input doubles the number of items to inspect, so the worst-case time is O(n). This differs from the case where the first item matches.

Looking for a product partner? Founders, teams, businesses: from problem framing to launch.