This page requires JavaScript to display.
A
Unpacking...
← Advanced Data Engineering
Advanced Data Engineering

DSA for Data Engineers

The data structures and algorithms data engineering interviews actually ask, each with a tested Python solution, its complexity and where it appears in real data systems.

Contents
1. What Data Engineering Interviews Expect 2. Time and Space Complexity 3. Arrays 4. Maths 5. Bit Manipulation 6. Strings 7. Binary Search 8. Recursion 9. Backtracking 10. Sorting 11. Two Pointers 12. Hashing 13. Stacks and Queues 14. Linked Lists 15. Binary Trees 16. Dynamic Programming 17. Graphs

1. What Data Engineering Interviews Expect

Product companies ask data engineers easier coding rounds than software engineers, but they do ask. Expect array, string, hashing and two-pointer problems most often, plus a graph or DP question for senior roles. The best preparation is learning the patterns: most questions are a known pattern in disguise.

If the problem says...Think of
"sorted array", "find a value or boundary"Binary search
"pair / triplet that sums to"Hashing, or two pointers if sorted
"longest / shortest substring or subarray"Sliding window
"top k", "k largest"Heap
"all combinations / subsets / permutations"Backtracking
"number of ways", "minimum cost", overlapping subproblemsDynamic programming
"dependencies", "order of tasks"Graph: topological sort
"connected groups", "same entity"Union-find or BFS/DFS
"next greater", "matching brackets"Stack
"process in arrival order", "shortest steps"Queue / BFS

Every solution on this page runs with assertions when the page is built. Practise by covering the code and solving each problem yourself first.

2. Time and Space Complexity

Big-O describes how cost grows with input size n, ignoring constants. It is how you compare approaches before writing code, and how you explain why a Spark job is slow.

Pattern / ideaWhen to use it
O(1)Hash lookup, array index
O(log n)Binary search, B-tree lookup, heap push/pop
O(n)One pass over data
O(n log n)Good sorting, sort-merge join
O(n²)Nested loops over the same data, naive pair comparison
O(2ⁿ), O(n!)All subsets / permutations
def count_ops(n):
    linear = n
    nested = n * n
    log = 0
    while n > 1:
        n //= 2
        log += 1
    return linear, nested, log

for n in [10, 1_000, 1_000_000]:
    lin, quad, lg = count_ops(n)
    print(f"n={n:>9,}: O(n)={lin:>13,}  O(n^2)={quad:>17,}  O(log n)={lg}")

# join algorithms for two tables of n and m rows
n, m = 1_000_000, 50_000
print(f"nested loop join ~{n*m:.1e} comparisons; hash join ~{n+m:,} operations")
Output
n=       10: O(n)=           10  O(n^2)=              100  O(log n)=3
n=    1,000: O(n)=        1,000  O(n^2)=        1,000,000  O(log n)=9
n=1,000,000: O(n)=    1,000,000  O(n^2)=1,000,000,000,000  O(log n)=19
nested loop join ~5.0e+10 comparisons; hash join ~1,050,000 operations

Where it shows up in data engineering: Join algorithms are complexity in practice: a nested-loop join is O(n·m), a hash join O(n+m), a sort-merge join O(n log n + m log m). Space complexity decides whether a hash table fits in executor memory or spills to disk.

3. Arrays

Arrays give O(1) access by index. The key techniques are prefix sums (answer any range sum in O(1) after one pass), sliding windows and Kadane's algorithm for the best contiguous run.

Pattern / ideaWhen to use it
Prefix sumsMany range-sum queries
Sliding windowBest or worst run of k consecutive values
KadaneMaximum subarray sum
def prefix_sums(a):
    ps = [0]
    for x in a:
        ps.append(ps[-1] + x)
    return ps

def range_sum(ps, i, j):  # sum of a[i..j] inclusive, O(1)
    return ps[j + 1] - ps[i]

def best_k_window(a, k):
    window = best = sum(a[:k])
    for i in range(k, len(a)):
        window += a[i] - a[i - k]        # slide: add new, drop old
        best = max(best, window)
    return best

def max_subarray(a):  # Kadane: best sum ending here, best overall
    best = cur = a[0]
    for x in a[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

daily_profit = [3, -2, 5, -1, 6, -8, 4, 2]
ps = prefix_sums(daily_profit)
assert range_sum(ps, 2, 4) == 10
assert best_k_window(daily_profit, 3) == 10
assert max_subarray(daily_profit) == 11
print("days 2-4:", range_sum(ps, 2, 4), "| best 3-day run:", best_k_window(daily_profit, 3),
      "| best run of any length:", max_subarray(daily_profit))
Output
days 2-4: 10 | best 3-day run: 10 | best run of any length: 11

Prefix sums: O(n) build, O(1) per query. Sliding window and Kadane: O(n) time, O(1) extra space.

Where it shows up in data engineering: Running totals and moving averages are prefix sums and sliding windows; SQL window functions SUM() OVER (ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) implement exactly this.

4. Maths

Common maths in interviews: GCD and LCM, primes, modular arithmetic, fast exponentiation, and probability-based tricks such as reservoir sampling.

Pattern / ideaWhen to use it
Euclid's GCDFractions, cycles, scheduling
Sieve of EratosthenesAll primes up to n
Modular arithmeticHash partitioning, overflow-safe counting
Reservoir samplingUniform sample from a stream of unknown length
import random

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def sieve(n):
    is_prime = [True] * (n + 1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n ** 0.5) + 1):
        if is_prime[i]:
            is_prime[i * i::i] = [False] * len(is_prime[i * i::i])
    return [i for i, p in enumerate(is_prime) if p]

def reservoir_sample(stream, k, seed=7):
    rng = random.Random(seed)
    sample = []
    for i, item in enumerate(stream):
        if i < k:
            sample.append(item)
        else:
            j = rng.randint(0, i)  # keep item with probability k/(i+1)
            if j < k:
                sample[j] = item
    return sample

assert gcd(84, 36) == 12 and 84 * 36 // gcd(84, 36) == 252
assert sieve(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
assert pow(7, 128, 13) == 3  # fast modular exponentiation
s = reservoir_sample(range(1_000_000), 5)
assert len(s) == 5
print("gcd:", gcd(84, 36), "| primes to 30:", sieve(30), "| sample of 5 from 1M:", s)
Output
gcd: 12 | primes to 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] | sample of 5 from 1M: [241991, 265413, 441586, 819859, 241860]

Where it shows up in data engineering: Partitioning by hash(key) % n is modular arithmetic; sampling a huge stream for data profiling or test data uses reservoir sampling (Spark's sample and approxQuantile rely on similar ideas).

5. Bit Manipulation

Bits give compact sets and fast tricks: x & (x-1) clears the lowest set bit, XOR cancels equal values, and a bit array can represent millions of flags in a few kilobytes.

Pattern / ideaWhen to use it
x & (x-1)Power-of-two check, counting set bits
XORFind the single unpaired value
BitmasksPermissions, feature flags, subsets
Bloom filterProbabilistic "definitely not present" checks
import hashlib

def is_power_of_two(x):
    return x > 0 and x & (x - 1) == 0

def single_number(nums):  # every value appears twice except one
    r = 0
    for n in nums:
        r ^= n
    return r

READ, WRITE, ADMIN = 1, 2, 4
perms = READ | WRITE
assert is_power_of_two(64) and not is_power_of_two(96)
assert single_number([4, 1, 2, 1, 2]) == 4
assert perms & WRITE and not perms & ADMIN
print("bits in 0b1011:", bin(0b1011).count("1"), "| can write:", bool(perms & WRITE))

class BloomFilter:
    def __init__(self, size_bits=10_000, hashes=4):
        self.size, self.k, self.bits = size_bits, hashes, 0
    def _positions(self, item):
        for i in range(self.k):
            yield int(hashlib.sha256(f"{i}:{item}".encode()).hexdigest(), 16) % self.size
    def add(self, item):
        for pos in self._positions(item):
            self.bits |= 1 << pos
    def might_contain(self, item):
        return all(self.bits >> pos & 1 for pos in self._positions(item))

seen = BloomFilter()
for i in range(500):
    seen.add(f"order_{i}")
false_pos = sum(seen.might_contain(f"other_{i}") for i in range(10_000))
assert all(seen.might_contain(f"order_{i}") for i in range(500))  # never a false negative
print(f"bloom filter: 500 items in 10,000 bits, false-positive rate {false_pos / 10_000:.2%}")
Output
bits in 0b1011: 3 | can write: True
bloom filter: 500 items in 10,000 bits, false-positive rate 0.07%

Where it shows up in data engineering: Bloom filters let Parquet, Delta, HBase and Cassandra skip files or blocks that definitely do not contain a key; bitmaps power bitmap indexes and HyperLogLog-style distinct counts.

6. Strings

String problems usually combine hashing (character counts) with sliding windows. Remember strings are immutable in Python: build lists and "".join them instead of concatenating in a loop.

Pattern / ideaWhen to use it
Character countsAnagrams, permutations of a pattern
Sliding window + set/mapLongest substring with a property
Two pointersPalindromes, reversing
from collections import Counter, defaultdict

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return sorted(groups.values())

def longest_unique_substring(s):
    last, start, best = {}, 0, 0
    for i, ch in enumerate(s):
        if ch in last and last[ch] >= start:
            start = last[ch] + 1  # move window past the repeat
        last[ch] = i
        best = max(best, i - start + 1)
    return best

def is_palindrome(s):
    t = [c.lower() for c in s if c.isalnum()]
    return t == t[::-1]

def compress(s):  # "aaabcc" -> "a3b1c2"
    out, i = [], 0
    while i < len(s):
        j = i
        while j < len(s) and s[j] == s[i]:
            j += 1
        out.append(f"{s[i]}{j - i}")
        i = j
    return "".join(out)

assert group_anagrams(["listen", "silent", "enlist", "data", "tada"]) == [["data", "tada"], ["listen", "silent", "enlist"]]
assert longest_unique_substring("abcabcbb") == 3
assert is_palindrome("A man, a plan, a canal: Panama")
assert compress("aaabcc") == "a3b1c2"
print(group_anagrams(["listen", "silent", "enlist", "data", "tada"]), longest_unique_substring("pwwkew"), compress("aaabcc"))
Output
[['data', 'tada'], ['listen', 'silent', 'enlist']] 3 a3b1c2

Where it shows up in data engineering: Normalising keys before joins (trim, case, accents), parsing logs, run-length encoding in columnar formats like Parquet, and fuzzy matching in MDM.

Binary search halves the search space each step: O(log n). Beyond "find x in a sorted array", it finds boundaries (first position where a condition becomes true) and searches an answer space ("smallest capacity that works").

Pattern / ideaWhen to use it
ClassicFind a value in sorted data
Lower boundFirst index where a[i] >= x
Search on the answerMinimise a value subject to a feasibility check
import bisect

def first_at_least(a, x):  # lower bound, written by hand
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def min_capacity(weights, days):  # smallest daily capacity to ship everything in order within `days`
    def feasible(cap):
        used, load = 1, 0
        for w in weights:
            if load + w > cap:
                used, load = used + 1, 0
            load += w
        return used <= days
    lo, hi = max(weights), sum(weights)
    while lo < hi:
        mid = (lo + hi) // 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

ts = [100, 200, 300, 400, 500]
assert first_at_least(ts, 250) == bisect.bisect_left(ts, 250) == 2
assert min_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15

# as-of lookup: which price version was valid at time t? (SCD2 / point-in-time join)
valid_from = ["2026-01-01", "2026-02-15", "2026-03-10"]
prices = [100, 110, 95]
def price_at(day):
    return prices[bisect.bisect_right(valid_from, day) - 1]
assert price_at("2026-03-01") == 110
print("lower bound of 250:", first_at_least(ts, 250), "| min capacity:", min_capacity(list(range(1, 11)), 5),
      "| price on 2026-03-01:", price_at("2026-03-01"))
Output
lower bound of 250: 2 | min capacity: 15 | price on 2026-03-01: 110

O(log n) time, O(1) space. Search on the answer costs O(n · log(range)).

Where it shows up in data engineering: B-tree index lookups, finding the right file by min/max key, point-in-time (as-of) joins against SCD2 versions, and git bisect to find the commit that broke a pipeline.

8. Recursion

A recursive function solves a problem by calling itself on smaller inputs until a base case. Add memoisation when subproblems repeat. Python's default recursion limit is about 1,000 frames, so very deep inputs need an iterative version.

Pattern / ideaWhen to use it
Divide and conquerMerge sort, tree problems
MemoisationOverlapping subproblems (leads into DP)
Nested structuresJSON, folders, hierarchies
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

def flatten(obj, prefix=""):
    """Flatten nested JSON into dotted column names, as when landing API data into a table."""
    flat = {}
    if isinstance(obj, dict):
        for k, v in obj.items():
            flat.update(flatten(v, f"{prefix}{k}."))
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            flat.update(flatten(v, f"{prefix}{i}."))
    else:
        flat[prefix[:-1]] = obj
    return flat

order = {"id": 7, "customer": {"name": "Asha", "address": {"city": "Pune"}}, "items": [{"sku": "A1", "qty": 2}]}
assert fib(50) == 12586269025
assert flatten(order)["customer.address.city"] == "Pune"
print(flatten(order))
Output
{'id': 7, 'customer.name': 'Asha', 'customer.address.city': 'Pune', 'items.0.sku': 'A1', 'items.0.qty': 2}

Where it shows up in data engineering: Flattening nested JSON from APIs, walking folder trees in object storage, traversing hierarchies (org charts, bills of materials), and recursive CTEs in SQL.

9. Backtracking

Backtracking builds candidates step by step and undoes the last choice when it cannot lead to a solution. It explores all combinations, so it is exponential; pruning invalid branches early is what makes it practical.

Pattern / ideaWhen to use it
SubsetsEvery combination of items
PermutationsEvery ordering
Constraint searchCombination sum, N-Queens, scheduling
def subsets(items):
    res, path = [], []
    def go(i):
        if i == len(items):
            res.append(path.copy())
            return
        go(i + 1)                       # skip items[i]
        path.append(items[i]); go(i + 1); path.pop()  # take items[i], then undo
    go(0)
    return res

def combination_sum(candidates, target):
    res, path = [], []
    def go(start, remaining):
        if remaining == 0:
            res.append(path.copy()); return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if c > remaining:
                break  # prune: candidates are sorted
            path.append(c); go(i, remaining - c); path.pop()
    go(0, target)
    return res

def n_queens(n):
    cols, d1, d2, count = set(), set(), set(), 0
    def place(r):
        nonlocal count
        if r == n:
            count += 1; return
        for c in range(n):
            if c in cols or r - c in d1 or r + c in d2:
                continue
            cols.add(c); d1.add(r - c); d2.add(r + c)
            place(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)
    place(0)
    return count

assert len(subsets(["a", "b", "c"])) == 8
assert combination_sum([2, 3, 5], 8) == [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
assert n_queens(6) == 4 and n_queens(8) == 92
print("subsets:", subsets(["a", "b", "c"]))
print("ways to make 8 from [2, 3, 5]:", combination_sum([2, 3, 5], 8), "| 8-queens solutions:", n_queens(8))
Output
subsets: [[], ['c'], ['b'], ['b', 'c'], ['a'], ['a', 'c'], ['a', 'b'], ['a', 'b', 'c']]
ways to make 8 from [2, 3, 5]: [[2, 2, 2, 2], [2, 3, 3], [3, 5]] | 8-queens solutions: 92

Where it shows up in data engineering: Generating test cases or parameter grids, exploring partitioning or scheduling options, and dependency resolution; in practice prefer heuristics or solvers at scale because backtracking is exponential.

10. Sorting

Python's built-in sort (Timsort) is O(n log n), stable, and fast on partially sorted data; use it with a key. Know merge sort (the basis of external sorting) and heaps for top-k without sorting everything.

Pattern / ideaWhen to use it
sorted(key=...)Custom and multi-column ordering
Merge sortStable O(n log n); merging sorted runs
Heap (heapq)Top-k in O(n log k); merging k sorted streams
Quickselectk-th element in average O(n)
import heapq

def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

orders = [("C2", 300), ("C1", 120), ("C3", 300), ("C1", 80)]
by_amount_desc_then_customer = sorted(orders, key=lambda o: (-o[1], o[0]))
top2 = heapq.nlargest(2, orders, key=lambda o: o[1])

# external merge sort: data too big for memory is sorted in chunks ("runs"), then k-way merged
runs = [sorted([9, 1, 7]), sorted([8, 2, 6]), sorted([5, 3, 4])]
merged = list(heapq.merge(*runs))

assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
assert merged == list(range(1, 10))
print(by_amount_desc_then_customer, "| top 2:", top2, "| k-way merge:", merged)
Output
[('C2', 300), ('C3', 300), ('C1', 120), ('C1', 80)] | top 2: [('C2', 300), ('C3', 300)] | k-way merge: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Merge sort O(n log n) time, O(n) space; heap top-k O(n log k); k-way merge O(n log k).

Where it shows up in data engineering: Spark sorts spill to disk in sorted runs and merge them (external merge sort); sort-merge joins, ORDER BY, window functions and clustering (Z-order) all depend on sorting; top-N queries use heaps.

11. Two Pointers

Two indices move through data, usually from both ends or at different speeds, turning many O(n²) problems into O(n). Works best on sorted data.

Pattern / ideaWhen to use it
Opposite endsPair sums in sorted data, palindromes
Same directionRemove duplicates, merge sorted lists
Sort then sweepMerge overlapping intervals
def pair_with_sum(sorted_nums, target):
    i, j = 0, len(sorted_nums) - 1
    while i < j:
        s = sorted_nums[i] + sorted_nums[j]
        if s == target:
            return sorted_nums[i], sorted_nums[j]
        i, j = (i + 1, j) if s < target else (i, j - 1)
    return None

def merge_intervals(intervals):
    out = []
    for start, end in sorted(intervals):
        if out and start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out

def sort_merge_join(left, right):
    """Join two lists of (key, value) sorted by key, as a sort-merge join does."""
    i = j = 0
    out = []
    while i < len(left) and j < len(right):
        if left[i][0] < right[j][0]:
            i += 1
        elif left[i][0] > right[j][0]:
            j += 1
        else:
            k = left[i][0]
            i2 = i
            while i2 < len(left) and left[i2][0] == k:
                j2 = j
                while j2 < len(right) and right[j2][0] == k:
                    out.append((k, left[i2][1], right[j2][1])); j2 += 1
                i2 += 1
            i, j = i2, j2
    return out

assert pair_with_sum([1, 3, 4, 6, 9], 10) == (1, 9)
assert merge_intervals([[1, 3], [2, 6], [8, 10], [9, 12]]) == [[1, 6], [8, 12]]
orders = [(1, "o1"), (2, "o2"), (2, "o3"), (4, "o4")]
customers = [(1, "Asha"), (2, "Ravi"), (3, "Meera")]
assert sort_merge_join(orders, customers) == [(1, "o1", "Asha"), (2, "o2", "Ravi"), (2, "o3", "Ravi")]
print("pair:", pair_with_sum([1, 3, 4, 6, 9], 10), "| merged:", merge_intervals([[1, 3], [2, 6], [8, 10], [9, 12]]))
print("sort-merge join:", sort_merge_join(orders, customers))
Output
pair: (1, 9) | merged: [[1, 6], [8, 12]]
sort-merge join: [(1, 'o1', 'Asha'), (2, 'o2', 'Ravi'), (2, 'o3', 'Ravi')]

Where it shows up in data engineering: The sort-merge join used by Spark and databases for two large tables is exactly the two-pointer merge above; merging overlapping intervals is sessionisation and SCD validity-range compaction.

12. Hashing

Hash tables (Python dict and set) give average O(1) insert and lookup. They are the single most useful interview tool: counting, deduplication, lookups and joins.

Pattern / ideaWhen to use it
Seen-setDuplicates, first repeat
Complement mapTwo-sum
CounterFrequencies, top-k
Hash joinJoin a small table to a big one
from collections import Counter

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return seen[target - n], i
        seen[n] = i

def first_non_repeating(s):
    counts = Counter(s)
    return next((c for c in s if counts[c] == 1), None)

def hash_join(big, small, key):
    build = {}
    for row in small:  # build phase: hash the smaller side
        build.setdefault(row[key], []).append(row)
    return [{**b, **s} for b in big for s in build.get(b[key], [])]  # probe phase

assert two_sum([2, 7, 11, 15], 9) == (0, 1)
assert first_non_repeating("swiss") == "w"
events = ["login", "view", "view", "buy", "view", "login"]
assert Counter(events).most_common(1) == [("view", 3)]
orders = [{"order_id": 1, "cid": "C1"}, {"order_id": 2, "cid": "C2"}, {"order_id": 3, "cid": "C9"}]
customers = [{"cid": "C1", "city": "Pune"}, {"cid": "C2", "city": "Delhi"}]
joined = hash_join(orders, customers, "cid")
assert [r["order_id"] for r in joined] == [1, 2]
print("two-sum:", two_sum([2, 7, 11, 15], 9), "| top event:", Counter(events).most_common(1), "| hash join:", joined)
Output
two-sum: (0, 1) | top event: [('view', 3)] | hash join: [{'order_id': 1, 'cid': 'C1', 'city': 'Pune'}, {'order_id': 2, 'cid': 'C2', 'city': 'Delhi'}]

Average O(1) per operation, O(n) space; worst case degrades with many collisions or skewed keys.

Where it shows up in data engineering: Hash joins and broadcast joins, hash partitioning in Spark and Kafka, deduplication by key, GROUP BY via hash aggregation, and distinct counts.

13. Stacks and Queues

A stack is last-in-first-out (use a list); a queue is first-in-first-out (use collections.deque, not a list, for O(1) pops from the front). A monotonic stack answers "next greater element" in O(n).

Pattern / ideaWhen to use it
StackMatching brackets, undo, DFS
Monotonic stackNext greater / smaller element
QueueBFS, task processing in order
Monotonic dequeSliding window maximum
from collections import deque

def valid_brackets(s):
    pairs, stack = {")": "(", "]": "[", "}": "{"}, []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

def next_greater(nums):
    res, stack = [-1] * len(nums), []  # stack holds indices of a decreasing run
    for i, n in enumerate(nums):
        while stack and nums[stack[-1]] < n:
            res[stack.pop()] = n
        stack.append(i)
    return res

def window_max(nums, k):
    dq, out = deque(), []
    for i, n in enumerate(nums):
        while dq and nums[dq[-1]] <= n:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

assert valid_brackets("{[()()]}") and not valid_brackets("([)]")
assert next_greater([73, 74, 75, 71, 69, 72, 76]) == [74, 75, 76, 72, 72, 76, -1]
assert window_max([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
print("next warmer temperature:", next_greater([73, 74, 75, 71, 69, 72, 76]),
      "| rolling 3-max:", window_max([1, 3, -1, -3, 5, 3, 6, 7], 3))
Output
next warmer temperature: [74, 75, 76, 72, 72, 76, -1] | rolling 3-max: [3, 3, 5, 5, 6, 7]

Where it shows up in data engineering: Message queues (SQS, Kafka consumers) and task queues in orchestrators are FIFO queues; validating nested expressions and parsing SQL use stacks; rolling maximum metrics use the monotonic deque.

14. Linked Lists

A linked list stores nodes that point to the next node: O(1) insert and delete given a node, O(n) access by position. Interview classics use pointer manipulation: reverse, detect cycles, merge.

Pattern / ideaWhen to use it
Reverse in placePointer re-wiring
Fast and slow pointersCycle detection, middle node
Dummy headMerging lists cleanly
Hash map + doubly linked listLRU cache
from collections import OrderedDict

class Node:
    def __init__(self, val, nxt=None):
        self.val, self.next = val, nxt

def build(vals):
    head = None
    for v in reversed(vals):
        head = Node(v, head)
    return head

def to_list(head):
    out = []
    while head:
        out.append(head.val); head = head.next
    return out

def reverse(head):
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False

class LRUCache:
    def __init__(self, capacity):
        self.cap, self.data = capacity, OrderedDict()
    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)  # mark as most recently used
        return self.data[key]
    def put(self, key, value):
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.cap:
            self.data.popitem(last=False)  # evict least recently used

assert to_list(reverse(build([1, 2, 3, 4]))) == [4, 3, 2, 1]
loop = build([1, 2, 3]); loop.next.next.next = loop.next
assert has_cycle(loop) and not has_cycle(build([1, 2, 3]))
cache = LRUCache(2); cache.put("a", 1); cache.put("b", 2); cache.get("a"); cache.put("c", 3)
assert list(cache.data) == ["a", "c"]  # "b" was least recently used
print("reversed:", to_list(reverse(build([1, 2, 3, 4]))), "| LRU keeps:", list(cache.data))
Output
reversed: [4, 3, 2, 1] | LRU keeps: ['a', 'c']

Where it shows up in data engineering: LRU caches (Spark block manager, database buffer pools, metadata caches), write-ahead logs and Kafka segments are append-only linked structures; cycle detection finds circular references in lineage or hierarchy data.

15. Binary Trees

A binary tree node has up to two children. Traversals (pre-, in-, post-order with DFS; level order with BFS) solve most problems. In a binary search tree, left < node < right, so in-order traversal returns sorted values.

Pattern / ideaWhen to use it
DFS recursionDepth, path sums, validation
BFS by levelLevel order, minimum depth
BST propertySearch, range queries, validation
LCACommon manager, common ancestor category
from collections import deque

class T:
    def __init__(self, v, left=None, right=None):
        self.v, self.left, self.right = v, left, right

#        8
#      /   \
#     3     10
#    / \      \
#   1   6      14
root = T(8, T(3, T(1), T(6)), T(10, None, T(14)))

def inorder(n):
    return inorder(n.left) + [n.v] + inorder(n.right) if n else []

def depth(n):
    return 1 + max(depth(n.left), depth(n.right)) if n else 0

def levels(n):
    out, q = [], deque([n])
    while q:
        out.append([x.v for x in q])
        q = deque(c for x in q for c in (x.left, x.right) if c)
    return out

def is_bst(n, lo=float("-inf"), hi=float("inf")):
    return not n or (lo < n.v < hi and is_bst(n.left, lo, n.v) and is_bst(n.right, n.v, hi))

def lca_bst(n, a, b):
    while n:
        if a < n.v and b < n.v:
            n = n.left
        elif a > n.v and b > n.v:
            n = n.right
        else:
            return n.v

assert inorder(root) == [1, 3, 6, 8, 10, 14]
assert depth(root) == 3 and levels(root) == [[8], [3, 10], [1, 6, 14]]
assert is_bst(root) and lca_bst(root, 1, 6) == 3 and lca_bst(root, 6, 14) == 8
print("in-order:", inorder(root), "| levels:", levels(root), "| LCA(1,6):", lca_bst(root, 1, 6))
Output
in-order: [1, 3, 6, 8, 10, 14] | levels: [[8], [3, 10], [1, 6, 14]] | LCA(1,6): 3

Where it shows up in data engineering: B-tree and B+tree indexes generalise binary search trees to wide nodes on disk; query plans are trees; organisational and product hierarchies are trees queried with recursive CTEs.

16. Dynamic Programming

Dynamic programming solves problems with overlapping subproblems and optimal substructure by storing answers to subproblems. Define the state, the recurrence and the base case, then fill a table bottom-up (or memoise top-down).

Pattern / ideaWhen to use it
1-D DPClimbing stairs, house robber
Unbounded knapsackCoin change, minimum cost
2-D DP on stringsEdit distance, longest common subsequence
LISLongest increasing subsequence
def coin_change(coins, amount):
    INF = float("inf")
    dp = [0] + [INF] * amount  # dp[a] = fewest coins to make a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a:
                dp[a] = min(dp[a], dp[a - c] + 1)
    return dp[amount] if dp[amount] != INF else -1

def edit_distance(a, b):
    dp = list(range(len(b) + 1))  # one rolling row: O(len(b)) space
    for i in range(1, len(a) + 1):
        prev, dp[0] = dp[0], i
        for j in range(1, len(b) + 1):
            cur = dp[j]
            dp[j] = prev if a[i - 1] == b[j - 1] else 1 + min(prev, dp[j], dp[j - 1])
            prev = cur
    return dp[-1]

def house_robber(values):  # max sum with no two adjacent
    take, skip = 0, 0
    for v in values:
        take, skip = skip + v, max(take, skip)
    return max(take, skip)

assert coin_change([1, 5, 10, 25], 63) == 6 and coin_change([2], 3) == -1
assert edit_distance("kitten", "sitting") == 3
assert house_robber([2, 7, 9, 3, 1]) == 12
pairs = [("Ravi Kumar", "Ravi Kumarr"), ("Acme Bank Ltd", "ACME Bank Limited"), ("Pune", "Mumbai")]
for x, y in pairs:
    d = edit_distance(x.lower(), y.lower())
    sim = 1 - d / max(len(x), len(y))
    print(f"{x!r:18} vs {y!r:20} distance {d:>2}, similarity {sim:.0%}")
Output
'Ravi Kumar'       vs 'Ravi Kumarr'        distance  1, similarity 91%
'Acme Bank Ltd'    vs 'ACME Bank Limited'  distance  4, similarity 76%
'Pune'             vs 'Mumbai'             distance  5, similarity 17%

Coin change O(amount × coins); edit distance O(m × n) time, O(n) space with a rolling row.

Where it shows up in data engineering: Edit distance (Levenshtein) powers fuzzy matching in MDM and entity resolution; DP-style optimisation appears in query planners (join ordering) and in resource allocation and scheduling problems.

17. Graphs

A graph has nodes and edges, stored as an adjacency list. BFS finds shortest paths in unweighted graphs, DFS explores and detects cycles, topological sort orders dependencies, Dijkstra handles weighted shortest paths, and union-find tracks connected groups.

Pattern / ideaWhen to use it
BFSFewest hops, levels of connection
Topological sort (Kahn)Task scheduling, build order, cycle detection
DijkstraCheapest route with non-negative weights
Union-findConnected components, grouping matched records
import heapq
from collections import deque, defaultdict

def topo_sort(deps):  # deps: task -> set of prerequisites
    indegree = {t: len(p) for t, p in deps.items()}
    children = defaultdict(list)
    for t, ps in deps.items():
        for p in ps:
            children[p].append(t)
    q, order = deque(sorted(t for t, d in indegree.items() if d == 0)), []
    while q:
        t = q.popleft(); order.append(t)
        for c in children[t]:
            indegree[c] -= 1
            if indegree[c] == 0:
                q.append(c)
    if len(order) != len(deps):
        raise ValueError("cycle detected: not a DAG")
    return order

def dijkstra(graph, src):
    dist, heap = {src: 0}, [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue
        for v, w in graph[u]:
            if d + w < dist.get(v, float("inf")):
                dist[v] = d + w
                heapq.heappush(heap, (d + w, v))
    return dist

class UnionFind:
    def __init__(self):
        self.parent = {}
    def find(self, x):
        self.parent.setdefault(x, x)
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x
    def union(self, a, b):
        self.parent[self.find(a)] = self.find(b)

pipeline = {"extract": set(), "clean": {"extract"}, "dims": {"clean"}, "facts": {"clean", "dims"}, "report": {"facts"}}
assert topo_sort(pipeline) == ["extract", "clean", "dims", "facts", "report"]
try:
    topo_sort({"a": {"b"}, "b": {"a"}})
except ValueError as e:
    print("cyclic graph rejected:", e)

roads = {"A": [("B", 4), ("C", 1)], "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": []}
assert dijkstra(roads, "A") == {"A": 0, "C": 1, "B": 3, "D": 4}

# entity resolution: records linked by shared email or phone end up in one group
uf = UnionFind()
for a, b in [("crm_1", "web_7"), ("web_7", "loyalty_3"), ("crm_2", "web_9")]:
    uf.union(a, b)
groups = defaultdict(list)
for rec in ["crm_1", "web_7", "loyalty_3", "crm_2", "web_9", "crm_5"]:
    groups[uf.find(rec)].append(rec)
print("run order:", topo_sort(pipeline))
print("shortest distances from A:", dijkstra(roads, "A"))
print("customer groups:", sorted(groups.values(), key=len, reverse=True))
Output
cyclic graph rejected: cycle detected: not a DAG
run order: ['extract', 'clean', 'dims', 'facts', 'report']
shortest distances from A: {'A': 0, 'B': 3, 'C': 1, 'D': 4}
customer groups: [['crm_1', 'web_7', 'loyalty_3'], ['crm_2', 'web_9'], ['crm_5']]

BFS/DFS and topological sort O(V + E); Dijkstra O((V + E) log V) with a heap; union-find nearly O(1) per operation with path compression.

Where it shows up in data engineering: Airflow, dbt and Spark all schedule work by topological sort of a DAG; lineage is a graph walked by BFS/DFS for impact analysis; union-find (connected components) groups matched records in MDM and identity resolution; route and network problems use Dijkstra.