Complexity and efficiency · 3 / 15 Theory

Choosing the right structure

Often the algorithm is the same and what changes the speed is where you store the data. Knowing the cost of each structure's operations lets you choose well without effort.

Costs of the usual operations

Operationlistset / dictdeque
Access by position x[i]O(1)—O(n) in the middle
Add at the endO(1)O(1)O(1)
Add or remove at the startO(n)—O(1)
Know whether a value is there (in)O(n)O(1)O(n)
Remove a valueO(n)O(1)O(n)
Go over everythingO(n)O(n)O(n)

Notice the two big differences: in on a list goes through the whole list, and removing the first element forces the rest to shift.

in on a list versus a set

def common_slow(a, b):
    return [x for x in a if x in b]      # 'in' on a list: O(n) each time, O(n·m) overall

def common_fast(a, b):
    as_set = set(b)                      # built once: O(m)
    return [x for x in a if x in as_set]   # each 'in' is O(1): O(n + m) overall

a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7]
print(common_slow(a, b))    # [4, 5]
print(common_fast(a, b))    # [4, 5]

The result is the same, but with lists of a million elements one version takes seconds and the other minutes. You compare them with numbers in Efficient intersection.

A dictionary avoids the inner loop

The problem of finding two numbers that add up to a target is solved with two loops in O(n²). If you store in a dictionary what you have already seen, a single pass is enough:

def two_sum(values, target):
    seen = {}
    for j, v in enumerate(values):
        i = seen.get(target - v)
        if i is not None:
            return i, j
        seen.setdefault(v, j)
    return None

print(two_sum([2, 7, 11, 15], 9))   # (0, 1)

The idea of "remembering what you have seen" also works for First duplicate and for Two-number sum. It is one of the most profitable techniques in programming.

deque for queues

from collections import deque

queue = list(range(5))
print(queue.pop(0))       # 0   O(n): shifts all the others

queue2 = deque(range(5))
print(queue2.popleft())   # 0   O(1)

Building text with join

Strings are immutable: s += "x" creates a new string and copies the old one, so concatenating in a loop is O(n²). "".join(items) builds the result at once, in O(n).

parts = [str(i) for i in range(5)]

slow = ""
for p in parts:
    slow += p               # copies the text on every turn

fast = "".join(parts)      # a single construction

print(slow == fast, fast)   # True 01234

Sort once instead of searching many times

If you are going to do many searches on the same data, it may be worth sorting it once (O(n log n)) and using binary search (O(log n) each), or converting it into a set or dict. With a single search, on the other hand, walking the list is the cheapest.

Rule of thumb

  • Do you need to know whether something is there? → set or dict.
  • Do you need to count or group by key? → dict or Counter.
  • Do you need to add and remove at both ends? → deque.
  • Do you need the minimum or maximum repeatedly? → heapq.
  • Do you need an order and access by position? → list.