Python Algorithms and ComplexityGet Certified
What Is an Algorithm?
An algorithm is a clear, step-by-step method for solving a problem, such as finding a name in a list, sorting a set of scores, or making change for a purchase. Most problems can be solved by several different algorithms, and they can differ enormously in speed: one may finish a task in a blink while another needs minutes on the same data. Complexity is the way that programmers describe this difference, by asking how the amount of work grows when the amount of data grows. Learning to compare algorithms helps you write programs that stay fast when a list grows from ten items to ten million.
- Searching: linear search checks every item, and binary search halves the problem at each step.
- Big O notation: a short way to describe how the work grows, such as
O(1),O(log n),O(n), andO(n²). - Sorting: bubble sort is simple but slow, while merge sort is much faster on large lists.
- Recursion and memoization: a function that calls itself, and a cache that avoids repeated work.
- Greedy algorithms: make the best choice at each step, as in making change with the fewest coins.
- Time and space trade-offs: use more memory, such as a set, to save time.
Linear Search: Checking Every Item
The simplest way to find something in a list is to look at the items one by one from the beginning until you find it or reach the end. This method is called linear search, and it works on any list, sorted or not. In the best case the target is the first item, and in the worst case it is the last one or is missing, so the number of steps can be as large as the length of the list. If the list doubles in size, the worst-case work doubles as well, and this steady growth is called linear time, written O(n).
Try It: Finding a City in a List
Click Test My Code. Search for "Austin" and notice how few steps the very first item needs.
-1 when the city is missing. Three searches show the middle, the worst, and the missing case.cities = ["Austin", "Boston", "Chicago", "Denver", "Miami", "Seattle", "Tampa"]
def linear_search(items, target):
steps = 0
for index, item in enumerate(items):
steps += 1
if item == target:
return index, steps
return -1, steps
print(linear_search(cities, "Denver"))
print(linear_search(cities, "Tampa"))
print(linear_search(cities, "Phoenix"))enumerate() gives each item together with its position.-1 and the steps that it needed.(3, 4).(6, 7).(-1, 7).Binary Search: Cutting the Problem in Half
If a list is already sorted, you can search it far more cleverly. Binary search looks at the middle item first: if it is the target, you are done, and if the target is smaller, you can throw away the whole upper half, and the other way around. Each step halves the remaining items, so even a list of a million items needs only about twenty steps. This growth is called logarithmic time, written O(log n), and it is one of the most important ideas in computer science. The only requirement is that the list must be sorted first.
Try It: Searching a List of 1,000 Numbers
Click Test My Code. Search for 1000 and count how many steps it needs, compared with the thousand steps of a linear search.
def binary_search(items, target):
low, high = 0, len(items) - 1
steps = 0
while low <= high:
steps += 1
mid = (low + high) // 2
if items[mid] == target:
return mid, steps
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1, steps
numbers = list(range(1, 1001))
print(binary_search(numbers, 1))
print(binary_search(numbers, 500))
print(binary_search(numbers, 1001))low and high mark the part of the list that can still contain the target. At the start, it is the whole list.low has not passed high, there are still items to examine.// gives the position in the middle of the remaining range.low above the middle throws away every item at or below it.high below the middle throws away the upper half.-1 and the steps.range(1, 1001) produces the numbers from 1 to 1000, and list() turns them into a sorted list.(0, 9).(499, 1).(-1, 10).Big O Notation: How the Work Grows
Big O notation describes how the number of steps of an algorithm grows as the size of the input, usually called n, grows. It ignores small details such as the speed of the computer and looks only at the shape of the growth. An O(1) algorithm needs the same work for any input, an O(n) algorithm needs work in proportion to the input, and an O(n²) algorithm, which usually has a loop inside a loop, needs a hundred times more work when the input becomes ten times larger. Knowing these shapes lets you predict which code will become slow before you ever run it.
O(1)is constant time, for example readingitems[0].O(log n)is logarithmic time, for example binary search.O(n)is linear time, for example a single loop over a list.O(n log n)is the speed of good sorting algorithms such as merge sort.O(n²)is quadratic time, for example two nested loops over the same list.
Try It: Counting Steps as the Data Grows
Click Test My Code. Add 5000 to the list of sizes and see how much faster the quadratic count grows than the linear one.
def constant_count(items):
first = items[0]
return 1
def linear_count(items):
count = 0
for item in items:
count += 1
return count
def quadratic_count(items):
count = 0
for first in items:
for second in items:
count += 1
return count
for size in [10, 100, 1000]:
data = list(range(size))
print(size, constant_count(data), linear_count(data), quadratic_count(data))O(1).O(n).O(n²).n times n.10 1 10 100, then 100 1 100 10000, and then 1000 1 1000 1000000. When the list is 100 times longer, the quadratic work is 10,000 times larger.Sorting with Bubble Sort
Sorting puts items in order, and it is one of the most common jobs in programming, because many other algorithms, such as binary search, need sorted data. Bubble sort is the easiest sorting method to understand: it walks through the list again and again, compares neighbors, and swaps them when they are in the wrong order, so the largest values slowly “bubble” to the end. Because it uses two nested loops, bubble sort needs O(n²) steps, which makes it too slow for large lists, but it is a good first example of how a sorting algorithm thinks. In real programs you would use Python’s built-in sorted() function.
Try It: Sorting Daily High Temperatures
Click Test My Code. Change the temperatures to a list that is already sorted and see that the swap count drops to zero.
def bubble_sort(values):
items = values.copy()
swaps = 0
for end in range(len(items) - 1, 0, -1):
for i in range(end):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swaps += 1
return items, swaps
temperatures = [72, 65, 80, 58, 91, 67]
sorted_temps, swaps = bubble_sort(temperatures)
print(sorted_temps)
print("Swaps:", swaps)
print("Original:", temperatures)copy() makes a new list, so that the original list stays unchanged.end counts down and the unsorted part gets shorter.[58, 65, 67, 72, 80, 91].Swaps: 7.Original: [72, 65, 80, 58, 91, 67].Faster Sorting with Merge Sort
Merge sort uses the strategy of divide and conquer: it splits the list in half, sorts each half by calling itself, and then merges the two sorted halves into one sorted list. Merging is quick, because you only need to compare the front items of the two halves and always take the smaller one. The list is split about log n times, and each level of merging touches all n items, so the total work is O(n log n), which is far better than bubble sort for large lists. Python’s own sorted() uses a related and highly tuned algorithm called Timsort.
Try It: Sorting Test Scores
Click Test My Code. Add a few more scores to the list and check that the result is still sorted.
merge_sort() function that splits a list until the pieces have one item, and a merge() function that combines two sorted lists into one. It sorts a list of eight test scores and prints the sorted result.def merge_sort(items):
if len(items) <= 1:
return items
middle = len(items) // 2
left = merge_sort(items[:middle])
right = merge_sort(items[middle:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]
scores = [88, 52, 95, 70, 63, 99, 41, 76]
print(merge_sort(scores))i and j point at the front item of each list. Both start at zero.[41, 52, 63, 70, 76, 88, 95, 99].Recursion and Memoization
A recursive function solves a problem by calling itself on a smaller version of the same problem, and the Fibonacci numbers are the classic example, because each number is the sum of the two before it. The straightforward recursive version is very wasteful, since it calculates the same values again and again, and its work roughly doubles with every step. Memoization fixes this by saving each result in a dictionary the first time it is calculated, so that every later request is answered instantly. This is a simple form of dynamic programming, and it turns an exponentially slow algorithm into a linear one.
Try It: Counting Fibonacci Calls
Click Test My Code. Change 20 to 25 in the last two lines and compare how the two call counts react.
calls = 0
def slow_fib(n):
global calls
calls += 1
if n < 2:
return n
return slow_fib(n - 1) + slow_fib(n - 2)
memo = {}
fast_calls = 0
def fast_fib(n):
global fast_calls
fast_calls += 1
if n in memo:
return memo[n]
if n < 2:
return n
memo[n] = fast_fib(n - 1) + fast_fib(n - 2)
return memo[n]
print(slow_fib(20), calls)
print(fast_fib(20), fast_calls)slow_fib() is called.n in the Fibonacci sequence.global statement lets the function change the variable outside of it.n as the key.slow_fib().n is already stored, no further work is needed.6765 21891.6765 39.Greedy Algorithms
A greedy algorithm builds a solution one step at a time and always takes the choice that looks best right now, without ever looking back. Making change is the classic example: to pay out an amount with as few coins as possible, you give the biggest coin that still fits, and then repeat with what remains. Greedy algorithms are usually fast and short, and for the U.S. coin system of 25, 10, 5, and 1 cents they give the best possible answer. For some other problems and coin systems, greedy choices can miss the best solution, so you must always check that the method really works for the problem at hand.
Try It: Making Change with Coins
Click Test My Code. Try make_change(68) and check by hand that the coins add up to 68 cents.
def make_change(cents):
coins = [25, 10, 5, 1]
result = {}
for coin in coins:
count, cents = divmod(cents, coin)
if count:
result[coin] = count
return result
print(make_change(87))
print(make_change(41))
print(make_change(99))divmod() returns the number of whole coins and the remaining cents in one step.{25: 3, 10: 1, 1: 2}.{25: 1, 10: 1, 5: 1, 1: 1}.{25: 3, 10: 2, 1: 4}.Trading Memory for Speed
Many algorithms become dramatically faster when you let them use a little more memory. A set or a dictionary in Python can tell you in about one step whether a value is present, while looking through a list takes a step for every item. This idea, called a time and space trade-off, turns many O(n²) algorithms into O(n) ones. A well-known example is the “two sum” problem, in which you look for two numbers in a list that add up to a given total: the slow way tries every pair, and the fast way remembers what it has seen so far.
- Looking up a value in a set or dictionary is
O(1)on average. - Looking up a value in a list is
O(n). - A set uses extra memory, but it can replace an entire inner loop.
- Always ask: “What do I keep looking up again and again?”
Try It: Two Prices That Fit a Budget
Click Test My Code. Change the budget to 55 and see that both methods report that no pair exists.
prices = [12, 7, 25, 3, 18, 9, 30]
budget = 27
def pair_slow(items, target):
checks = 0
for i in range(len(items)):
for j in range(i + 1, len(items)):
checks += 1
if items[i] + items[j] == target:
return (items[i], items[j]), checks
return None, checks
def pair_fast(items, target):
seen = set()
checks = 0
for price in items:
checks += 1
if target - price in seen:
return (target - price, price), checks
seen.add(price)
return None, checks
print(pair_slow(prices, budget))
print(pair_fast(prices, budget))None and the checks.target - price. Looking for it in a set takes about one step.None and the checks.((18, 9), 19).((18, 9), 6).Tip: Before you try to make a program faster, make it correct, and then find out which part is really slow. Count steps as in these examples, or measure the time withtime.perf_counter()or thetimeitmodule. Prefer Python’s built-in tools such assorted(),min(),sum(), sets, and dictionaries, because they are already well optimized.
Using Algorithms with User Input
Algorithms become more interesting when they react to what a user types. In the examples below, the program reads a whole number with int(), runs an algorithm on it, and reports not only the answer but also how many steps were needed. This is a good habit: when you print the number of steps, you can see the complexity at work, and you can check whether a change to your code really makes it faster. Remember that input() returns text, so always convert the answer before you do any arithmetic with it.
Try It: A Number Guessing Helper
The Program Input box is already filled with 73. Click Run Code straight away, then try 1 and 100 to see the best and the worst cases.
def guess_steps(secret):
low, high = 1, 100
steps = 0
while low <= high:
steps += 1
guess = (low + high) // 2
if guess == secret:
return steps
if guess < secret:
low = guess + 1
else:
high = guess - 1
return steps
secret = int(input("Pick a number from 1 to 100: "))
print(f"Found {secret} in {guess_steps(secret)} guesses")
print("A linear search could need up to 100 guesses")73, is converted from text to an integer.Found 73 in 6 guesses.Try It: A Prime Number Checker
The Program Input box is filled with 97. Click Run Code, then try 91 and see how quickly a non-prime is detected.
def is_prime(n):
if n < 2:
return False, 0
steps = 0
divisor = 2
while divisor * divisor <= n:
steps += 1
if n % divisor == 0:
return False, steps
divisor += 1
return True, steps
number = int(input("Enter a whole number: "))
prime, steps = is_prime(number)
if prime:
print(f"{number} is prime (checked {steps} divisors)")
else:
print(f"{number} is not prime (stopped after {steps} checks)")divisor * divisor <= n means that about the square root of n divisors are tried. The algorithm is O(√n).False and the number of steps.97, is converted from text to an integer.prime and steps.True.97 is prime (checked 8 divisors).91, the divisor 7 is found on the sixth step. The output is 91 is not prime (stopped after 6 checks).Common Mistakes with Algorithms
Most beginners make the same handful of mistakes when they first write searching, sorting, and recursive code, and almost all of them come from skipping a small detail. Some of the mistakes produce wrong answers, while others only make the program far slower than it needs to be, which is harder to notice on a small test list. The list below covers the problems that appear most often, and it is worth a quick read whenever a program works on ten items but becomes painfully slow on ten thousand.
- Using binary search on an unsorted list: it needs sorted data, and on an unsorted list it gives wrong answers. Sort first, or use linear search.
- Off-by-one errors in the boundaries: writing
low < highinstead oflow <= high, or forgetting the+ 1and- 1, can skip items or loop forever. - Forgetting the base case in recursion: without a stopping condition, a function calls itself until Python raises
RecursionError. - Repeating work in recursion: plain Fibonacci recomputes the same values again and again. Use memoization or
functools.lru_cache. - Hiding a loop inside a loop: an
intest on a list inside a loop is a second loop. Use a set for fast lookups. - Sorting inside a loop: calling
sorted()on every pass repeats expensive work. Sort once, outside the loop. - Trusting greedy choices without checking: a greedy method is not always optimal, for example with unusual coin values.
- Optimizing too early: measure first, because the slow part is often not where you expect.
Key Takeaways
Algorithms and complexity give you a way to think about programs that goes beyond whether the answer is correct: you also ask how the program behaves when the data grows. The skills in this lesson, such as counting steps, recognizing a nested loop, and replacing a list search by a set lookup, will serve you in every later project. The points below summarize the lesson, and they prepare you for the next one on stacks, queues, and trees, where you will learn to organize data in structures that make many algorithms simple. Remember them whenever a program feels slow.
- An algorithm is a step-by-step method for solving a problem, and different algorithms for the same problem can differ greatly in speed.
- Big O notation describes how the work grows with the input size:
O(1),O(log n),O(n),O(n log n), andO(n²). - Linear search is
O(n)and works on any list, while binary search isO(log n)but needs sorted data. - Bubble sort is
O(n²)and simple, while merge sort isO(n log n)and uses divide and conquer. In real code, usesorted(). - Recursion needs a base case, and memoization stores results so that repeated work is avoided.
- A greedy algorithm takes the best choice at every step, and it must be checked to see whether it gives an optimal answer.
- Sets and dictionaries trade a little memory for much faster lookups, and counting steps is a simple way to compare algorithms.
Frequently Asked Questions
These are the questions that students ask most often when they learn about algorithms and complexity in Python. The answers are brief and practical, and each idea appears in one of the examples above. If something is still unclear, try running one of the examples with a list that is ten times larger, and look at how the step counts change, because seeing the numbers grow is the fastest way to understand Big O notation.
What is an algorithm in Python?
An algorithm is a clear, step-by-step procedure for solving a problem, such as searching a list, sorting numbers, or making change. In Python you write an algorithm as a function or a short program. The same problem can often be solved by several algorithms that differ greatly in speed and memory use.
What is Big O notation?
Big O notation describes how the running time or the number of steps of an algorithm grows as the size of the input grows. For example, O(n) means the work grows in proportion to the input, and O(n squared) means the work grows with the square of the input. It ignores machine speed and small details and focuses on the shape of the growth.
What is the difference between linear search and binary search?
Linear search checks the items one by one and works on any list, taking O(n) steps. Binary search repeatedly checks the middle of a sorted list and discards half of the remaining items, taking only O(log n) steps. Binary search is much faster on large lists, but the list must be sorted first.
Why does binary search need a sorted list?
Binary search decides which half of the list to discard by comparing the middle item with the target. This only makes sense when the items are in order, because then every item in the discarded half is known to be too small or too large. On an unsorted list, the discarded half could contain the target.
Should I write my own sorting algorithm or use sorted()?
In real programs, use the built-in sorted() function or the list sort() method. They use Timsort, a fast and carefully tested algorithm with O(n log n) running time. Writing your own sorting algorithms, such as bubble sort or merge sort, is valuable for learning how algorithms work, but it is rarely needed in practice.
What are recursion and memoization?
Recursion means that a function solves a problem by calling itself on a smaller version of the same problem, and it needs a base case to stop. Memoization saves the result of each call in a dictionary, so that repeated calls with the same input are answered instantly. It can turn a very slow recursive function, such as plain Fibonacci, into a fast one.
What is a greedy algorithm?
A greedy algorithm builds a solution step by step and always makes the choice that looks best at the moment, without reconsidering it later. Making change with the largest coin first is an example. Greedy algorithms are fast and simple, but they only give the best answer for certain problems, so their correctness has to be checked.
How can I measure how fast my Python code is?
You can count the steps of the algorithm, as in the examples of this lesson, or measure the real time with time.perf_counter() or the timeit module. Run the code with several input sizes and watch how the time or the count grows. This shows you the complexity better than a single measurement does.