Python & data structures: learn the patterns

Fourteen explained patterns from the Cloud Engineer roadmap. Read the mechanism, trace the worked Python example, then try the independent challenge.

Weeks 5–7

Big-O and complexity

Big-O describes how the work grows as the input gets larger. It is a growth model, not a stopwatch. If you inspect every line in a log file once, doubling the number of lines roughly doubles the inspections: O(n). If you compare every line with every other line, the number of comparisons grows roughly fourfold when the input doubles: O(n²). Constants and input size still matter in real systems. A tiny nested loop may be fine; a network request in each iteration can dominate a theoretically efficient loop. Count the repeated operations, then state the assumptions behind that count.

def count_errors(lines):
    count = 0
    for line in lines:        # n inspections
        if "ERROR" in line:
            count += 1
    return count

# O(n) inspections; O(1) extra space.
# This assumes each line has bounded length.

Try it independently

Compare scanning a list for a username with checking a set. Explain expected lookup cost, preprocessing cost, and extra memory.

Weeks 6–8

Arrays and strings

A Python list keeps an ordered sequence. You can retrieve an element by index, but inserting at the front shifts later references. A string is an immutable sequence of characters: changing it creates a new string. This difference matters when building output repeatedly. Use list accumulation and join for many pieces instead of relying on repeated concatenation. Learn to distinguish the value from its position. In a log parser, the third column may mean an HTTP status only if the format guarantees it. Validate the format before indexing, and decide what should happen for missing or malformed data.

rows = ["200 /home", "503 /api", "bad-row"]
statuses = []
for row in rows:
    parts = row.split()
    if len(parts) == 2 and parts[0].isdigit():
        statuses.append(int(parts[0]))

print(statuses)  # [200, 503]

Try it independently

Write a function that returns the longest valid hostname in a list. Define behavior for an empty list and duplicate lengths.

Weeks 7–9

Hashmaps and sets

A dictionary maps a key to a value; a set keeps unique values. Hashing helps these structures find an entry without scanning the whole collection in the typical case. Keys must be hashable, so a mutable list cannot be a dictionary key. For a log summary, the endpoint is a natural key and the number of requests is its value. For deduplicating request IDs, a set is simpler because there is no additional value to store. Do not confuse deduplication with idempotency: remembering an ID in memory is not enough when processes restart or multiple workers act at once.

from collections import Counter

paths = ["/api", "/health", "/api", "/api"]
counts = Counter(paths)
print(counts["/api"])  # 3

seen_ids = set()
for request_id in ["r1", "r2", "r1"]:
    if request_id not in seen_ids:
        seen_ids.add(request_id)
        print("first seen:", request_id)

Try it independently

Count errors by service from structured records. Explain why a missing service label needs a deliberate policy.

Weeks 8–10

Two pointers

Two pointers track two positions that move through a sequence. The key is proving why moving a pointer cannot skip a valid answer. In a sorted list, if the sum of the leftmost and rightmost values is too small, increasing the left value is the only useful move. If the sum is too large, decrease the right value. This reasoning depends on sorted input. Without that property, the same movement can miss a solution. Two pointers are also useful for comparing characters from both ends or merging sorted streams. State the invariant before writing the loop.

def pair_sum(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None

print(pair_sum([2, 4, 7, 11], 13))  # (0, 3)

Try it independently

Test empty input, one element, repeated values, and an absent solution. Explain why sorting changes index meanings.

Weeks 9–11

Sliding window

A sliding window represents a contiguous portion of a sequence. Instead of recomputing every sum, remove the value that leaves and add the value that enters. For fixed-width request counts, this gives a rolling total in linear time. Variable-width windows need an additional rule for expanding and shrinking. Be careful with assumptions: a sum-based shrink rule that works for nonnegative values may fail when negative values are allowed. In observability, also distinguish a window of three samples from a window of three minutes. Irregular sample times can make those different measurements.

def rolling_totals(values, width):
    if width <= 0 or width > len(values):
        return []
    total = sum(values[:width])
    output = [total]
    for i in range(width, len(values)):
        total += values[i] - values[i - width]
        output.append(total)
    return output

print(rolling_totals([2, 5, 1, 4], 3))  # [8, 10]

Try it independently

Compute the busiest five-minute interval from evenly sampled request counts. Define the policy for missing samples.

Weeks 10–12

Stacks and queues

A stack returns the newest item first: last in, first out. A queue returns the oldest item first: first in, first out. A stack fits nested parsing or an undo history; a queue fits breadth-first traversal or a line of work waiting to be handled. Python lists work well for stack append/pop at the end. For queue behavior, use collections.deque instead of repeatedly removing index zero from a list. A local queue is only a data structure. A cloud messaging queue also needs durability, acknowledgement, retries, and duplicate handling. Keep those concerns separate when explaining SQS.

from collections import deque

stack = []
stack.append("open bracket")
print(stack.pop())

work = deque(["job-a", "job-b"])
work.append("job-c")
print(work.popleft())  # job-a

Try it independently

Validate balanced parentheses with a stack. Test an extra closing bracket and a leftover opening bracket.

Weeks 11–13

Linked lists

A linked list stores nodes connected by references. Unlike an indexed array, finding the tenth node generally requires following references from the start. Inserting after a node you already hold can be cheap, but locating that node may still take linear time. These are different costs. The most common beginner bug is overwriting the next reference before preserving it during reversal. Draw three nodes and label each reference before changing anything. This topic is useful for reasoning about pointers and state transitions even when ordinary cloud scripts are better served by Python lists or deques.

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node

def reverse(head):
    previous = None
    current = head
    while current is not None:
        following = current.next
        current.next = previous
        previous, current = current, following
    return previous

Try it independently

Trace reversal of A → B → C on paper. Explain what happens for an empty list and a one-node list.

Weeks 12–14

Binary search and sorting

Binary search repeatedly halves a search interval. It requires a sorted sequence or another monotonic property: once a condition becomes true, it stays true beyond a boundary. Each comparison eliminates half the remaining candidates, giving logarithmic search growth. Sorting first has a cost, so sorting once just to answer a single lookup may be worse than a simple scan. Binary search is especially useful when a sorted structure will answer many queries. Keep interval conventions consistent. Mixing inclusive and exclusive upper bounds is a common source of off-by-one errors and infinite loops.

def find_index(values, target):
    low, high = 0, len(values)  # high is exclusive
    while low < high:
        middle = (low + high) // 2
        if values[middle] < target:
            low = middle + 1
        else:
            high = middle
    if low < len(values) and values[low] == target:
        return low
    return -1

Try it independently

Find the first timestamp at or after a requested time in sorted events. State what is returned when no event qualifies.

Weeks 13–15

Recursion

A recursive function solves a problem by calling itself on a smaller problem. It needs a base case and progress toward that base case. The call stack remembers unfinished work, which means recursion uses memory even when you do not create a collection explicitly. Recursive traversal can express nested structures clearly, but very deep input may exceed Python’s recursion limit. Use an explicit stack when depth is untrusted or large. Never assume a filesystem traversal is automatically a tree: symbolic links and repeated references can create cycles, so real tools need a cycle policy.

def nested_total(value):
    if isinstance(value, int):
        return value
    if isinstance(value, list):
        return sum(nested_total(item) for item in value)
    raise TypeError("Expected an int or nested list")

print(nested_total([2, [3, [4]], 1]))  # 10

Try it independently

Explain the base case and shrinking input. Add tests for an empty list and an unexpected string.

Weeks 14–16

Trees and traversals

A tree organizes nodes in a parent-child hierarchy without cycles. Traversal determines the order in which you visit them. Preorder processes a parent before its children; postorder processes children before the parent. For dependency cleanup, postorder is often the useful mental model because dependants must be removed before their supporting structure. A binary search tree is a special kind of tree with ordering rules; an arbitrary tree does not provide sorted lookup. Draw a small hierarchy and write the expected order before implementing the traversal. For shared dependencies, use a graph rather than pretending the structure is a tree.

tree = {"root": ["api", "worker"],
        "api": ["cache"], "worker": [], "cache": []}

def preorder(node):
    print(node)
    for child in tree[node]:
        preorder(child)

preorder("root")  # root, api, cache, worker

Try it independently

Write a postorder traversal and compare its output. Explain why traversal order can matter during cleanup.

Weeks 15–17

BFS and DFS

Breadth-first search explores nearby nodes before more distant nodes using a queue. In an unweighted graph, it can find a shortest path by number of edges. Depth-first search follows one branch before backtracking, using recursion or a stack. Both need a visited set for graphs with cycles. Mark a node when you enqueue it in BFS to avoid adding it repeatedly. “Shortest” needs a definition: BFS does not minimize latency when links have different weights. In infrastructure reasoning, traversal can reveal reachable dependencies, but a graph edge alone does not prove a live network connection is allowed.

from collections import deque

def reachable(graph, start):
    seen = {start}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in graph.get(node, []):
            if neighbor not in seen:
                seen.add(neighbor)
                queue.append(neighbor)
    return seen

Try it independently

Add a cycle to a dependency graph and confirm traversal terminates. Extend BFS to record a path to a target.

Weeks 16–18

Heaps and priority queues

A heap efficiently returns the smallest or largest item without fully sorting the collection. Python heapq implements a min-heap, so the smallest priority comes out first. Pushing and popping have logarithmic cost; inspecting the smallest item is constant time. The internal list is not globally sorted, so do not read it as a ranking. A priority queue can schedule urgent work before routine work, but priority alone can starve low-priority jobs. Use a sequence number when equal priorities should preserve arrival order and to avoid comparing incompatible payload objects.

import heapq

work = []
heapq.heappush(work, (2, 0, "routine cleanup"))
heapq.heappush(work, (1, 1, "service incident"))
heapq.heappush(work, (2, 2, "documentation"))

while work:
    priority, sequence, task = heapq.heappop(work)
    print(task)

Try it independently

Keep the three largest request latencies using a size-three min-heap. Explain why this avoids sorting all samples.

Weeks 16–18

Graph fundamentals

A graph models entities as nodes and relationships as edges. Edges can be directed or undirected, weighted or unweighted. A deployment dependency graph is directed: the application depends on a database, which does not imply the database depends on the application. An adjacency list stores each node’s outgoing neighbors and works well for sparse graphs. Before choosing an algorithm, define what an edge means. Does it represent ownership, network reachability, request flow, or a prerequisite? Combining these meanings in one diagram can lead to incorrect operational conclusions. Cycles may be valid for request flows but problematic for a strict build order.

dependencies = {
    "api": ["database", "cache"],
    "worker": ["database", "queue"],
    "database": [], "cache": [], "queue": []
}

for service, requires in dependencies.items():
    print(service, "depends on", requires)

Try it independently

Draw a deployment graph, then a separate request-flow graph for the same app. Explain why their edges differ.

Weeks 16–18

Basic dynamic programming

Dynamic programming stores answers to overlapping subproblems instead of recalculating them. First define the state precisely. For a staircase where each move is one or two steps, ways[n] is the number of valid sequences reaching step n. The final move came from n−1 or n−2, so ways[n] = ways[n−1] + ways[n−2]. Base cases make the recurrence usable. A memoized recursive solution computes on demand; a bottom-up solution computes in dependency order. You can reduce memory when only the last two states matter. This pattern is optional unless target interviews require it; practical cloud automation remains the priority.

def ways_to_climb(n):
    if n < 0:
        return 0
    previous, current = 1, 1
    for step in range(2, n + 1):
        previous, current = current, previous + current
    return current

print(ways_to_climb(4))  # 5

Try it independently

List all five sequences for four steps. Explain the meaning of the state and why the recurrence counts each sequence once.

Explore the Cloud Engineer path