Skip to content
LeetQuant
F7 Programming and Algorithms Foundations

F7 · Programming and Algorithms Foundations · Lesson 2 of 6

Python Essentials for Interviews

The built-in containers and what each operation costs, comprehensions and generators, the collections module, sorting with keys, and the Python pitfalls interviewers like to probe.

18 min

Know what every line costs

In a screening round you are expected to write idiomatic Python and state its complexity. Most accidental O(n2)O(n^2) solutions come from one innocent-looking line, such as x in some_list inside a loop or lst.pop(0) used as a queue. Learn the cost of each container operation so you choose the container before you write the loop.

Operationlistdict / setcollections.deque
index a[i]O(1)O(1)key lookup O(1)O(1) avgO(n)O(n) in the middle
append at the endO(1)O(1) amortisedinsert O(1)O(1) avgO(1)O(1)
remove from the endpop() O(1)O(1)delete O(1)O(1) avgpop() O(1)O(1)
insert or remove at the frontO(n)O(n)n/aO(1)O(1)
membership x in cO(n)O(n)O(1)O(1) avgO(n)O(n)
slice a[i:j]O(j−i)O(j - i), makes a copyn/an/a
sortO(nlog⁡n)O(n \log n)n/an/a

Hash-based operations are O(1)O(1) on average; adversarial or badly hashed keys degrade them to O(n)O(n). len is O(1)O(1) for all three. Building a string with s += piece in a loop can cost O(n2)O(n^2) in total; collect the pieces in a list and call "".join(pieces) once.

Tuples, hashing, comprehensions and generators

  • Tuples are immutable and hashable if their contents are, so they can be dictionary keys and set members: seen.add((row, col)). Lists cannot.
  • Comprehensions build containers in one expression: [p * q for p, q in fills], {sym: 0 for sym in symbols}, {x % 7 for x in xs}. They are clearer and usually faster than an explicit loop with append.
  • Generators produce values lazily. sum(x * x for x in xs) never builds the list of squares, so it uses O(1)O(1) extra memory. A generator can be consumed once:
squares = (x * x for x in range(5))
print(sum(squares), sum(squares))   # 30 0

Write a generator function with yield when you want to stream records (ticks from a file, windows of a series) without holding them all in memory.

The collections module

Three classes from collections remove most boilerplate:

  • Counter: a dictionary of counts. Counter("mississippi").most_common(2) returns [('i', 4), ('s', 4)], and a missing key reads as 0 instead of raising KeyError.
  • defaultdict(list) or defaultdict(int): creates the default value on first access, so grouping is groups[key].append(item) with no if key not in groups check.
  • deque: a double-ended queue with O(1)O(1) append, appendleft, pop and popleft. Use it for BFS queues and sliding windows. deque(maxlen=3) keeps only the last three items pushed.

heapq (a min-heap on a plain list) completes the toolkit for top-kk and scheduling questions.

Worked example

count pairs that sum to a target

Given trade sizes [100, 200, 300, 100, 200], count the pairs of positions i<ji < j whose sizes sum to 300300. Give an O(n)O(n) solution.

Show solution

The brute force checks all (n2)\binom{n}{2} pairs, which is O(n2)O(n^2). Instead, scan once and keep a Counter of the sizes seen so far. When size ss arrives, every earlier occurrence of 300−s300 - s forms a pair with it.

from collections import Counter

def count_pairs(sizes: list[int], target: int) -> int:
    seen = Counter()
    pairs = 0
    for s in sizes:
        pairs += seen[target - s]   # missing keys read as 0
        seen[s] += 1
    return pairs

print(count_pairs([100, 200, 300, 100, 200], 300))   # 4

Trace: at the first 200 there is one earlier 100 (1 pair); 300 needs a 0 (none); the second 100 pairs with the earlier 200 (2 pairs); the second 200 pairs with both 100s (4 pairs). Updating seen after counting is what enforces i<ji < j and stops an element pairing with itself. Time O(n)O(n), space O(n)O(n).

Sorting with keys

sorted(xs, key=f) sorts by f(x), calling f once per element. Return a tuple to sort by several fields, and negate a numeric field to reverse just that field:

trades = [("b", 101.0, 3), ("a", 100.5, 1), ("c", 101.0, 2), ("d", 100.5, 5)]
# price ascending, then quantity descending
print(sorted(trades, key=lambda t: (t[1], -t[2])))
# [('d', 100.5, 5), ('a', 100.5, 1), ('b', 101.0, 3), ('c', 101.0, 2)]

Python's sort (Timsort) is stable: items with equal keys keep their input order. list.sort() sorts in place and returns None, so xs = xs.sort() is a classic bug.

Worked example

VWAP per symbol, ranked by volume

Trades arrive as (symbol, price, quantity):

trades = [("AAPL", 190.0, 100), ("MSFT", 410.0, 50), ("AAPL", 191.0, 300),
          ("MSFT", 409.0, 150), ("TSLA", 250.0, 200)]

Compute each symbol's volume-weighted average price and list symbols by total volume, largest first, breaking ties alphabetically.

Show solution

VWAP is ∑piqi/∑qi\sum p_i q_i / \sum q_i, so accumulate notional and volume per symbol in one pass with two defaultdicts, then divide.

from collections import defaultdict

notional = defaultdict(float)
volume = defaultdict(int)
for sym, px, qty in trades:
    notional[sym] += px * qty
    volume[sym] += qty

vwap = {s: notional[s] / volume[s] for s in notional}
ranked = sorted(volume.items(), key=lambda kv: (-kv[1], kv[0]))
print(vwap)    # {'AAPL': 190.75, 'MSFT': 409.25, 'TSLA': 250.0}
print(ranked)  # [('AAPL', 400), ('MSFT', 200), ('TSLA', 200)]

Check AAPL by hand: (190⋅100+191⋅300)/400=76,300/400=190.75(190 \cdot 100 + 191 \cdot 300)/400 = 76{,}300/400 = 190.75. MSFT and TSLA tie on 200 shares, and the key (-volume, symbol) puts MSFT first. The pass is O(n)O(n) and the ranking O(mlog⁡m)O(m \log m) for mm symbols.

Pitfalls interviewers probe

Mutable default arguments are evaluated once, when the function is defined, and shared between calls:

def append_to(x, bucket=[]):
    bucket.append(x)
    return bucket

print(append_to(1))   # [1]
print(append_to(2))   # [1, 2]  (the same list again)

The fix is bucket=None and if bucket is None: bucket = [] inside the body.

Aliasing. [[0] * 3] * 3 is three references to one row, so grid[0][0] = 1 gives [[1, 0, 0], [1, 0, 0], [1, 0, 0]]. Build rows independently: [[0] * 3 for _ in range(3)]. Likewise b = a does not copy a list; use a.copy() or a[:].

Late-binding closures. [lambda: i for i in range(3)] produces three functions that all return 2, because each looks up i when called. Bind the value with a default: lambda i=i: i.

Integers and floats.

  • int has arbitrary precision: 2**100 is exact and integer arithmetic never overflows.
  • / always returns a float; // is floor division and % takes the sign of the divisor: -7 // 2 == -4 and -7 % 2 == 1, while int(-7 / 2) == -3 truncates towards zero.
  • round uses round-half-to-even: round(2.5) == 2, round(3.5) == 4.
  • 0.1 + 0.2 == 0.3 is False; compare floats with math.isclose or work in integer ticks.
  • is tests identity, == tests equality. Use is only for None.

Knowledge check

What does -7 // 2 evaluate to in Python 3?

Knowledge check

A BFS loop processes n nodes and removes each one from the front of a Python list with queue.pop(0). What is the total cost of those removals, and what is the fix?

Knowledge check

def f(x, acc=[]): acc.append(x); return len(acc). What do the calls f(5), f(6), f(7, []) return, in that order?

Key takeaways

  • Lists are fast at the end and slow at the front and for membership; dicts and sets give O(1)O(1) average lookup; deques give O(1)O(1) at both ends.
  • Use comprehensions for building containers and generators for streaming; a generator is consumed once.
  • Counter, defaultdict and deque turn most counting, grouping and queue code into a few lines.
  • Sort with tuple keys and negation; Python's sort is stable and list.sort() returns None.
  • Watch mutable defaults, aliased nested lists, late-binding closures, floor division with negatives and half-to-even rounding.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).