← Interview prep

Algorithms interview questions

Problem-solving patterns, complexity, and coding-round staples.

100 questions · Page 4 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 4 of 5

Questions 61–80 of 100 · 0 of 20 on this page marked learned

61.algorithms-0061Hardsenior

Find the median from a data stream: support adding numbers and returning the current median, both efficiently.

Keep two heaps: a max-heap of the smaller half and a min-heap of the larger half, with the max-heap holding the same count or one more. Adding pushes through the max-heap into the min-heap and rebalances: O(log n). The median is the top of the max-heap, or the average of both tops: O(1). A sorted list with insort is the O(n)-per-insert baseline.

Full answer

Problem

Design MedianFinder with add(x) and median(). For an odd count the median is the middle value; for an even count it is the mean of the two middle values.

Example: add 1 (median 1.0), add 2 (median 1.5), add 3 (median 2.0).

Constraints: up to 5 * 10^4 calls; values from -10^5 to 10^5; median is only called when at least one value exists (the code raises otherwise).

Brute force

Maintain a sorted list and insert with binary search (bisect.insort). Finding the position is O(log n), but shifting elements makes each insert O(n). Sorting on every median call is O(n log n).

Optimal approach

Two heaps:

  • low: max-heap (store negatives in Python) holding the smaller half.
  • high: min-heap holding the larger half.

add(x): push x into low, pop the largest of low and push it into high, then if high has more items than low, move the smallest of high back. median(): if low is larger, return its top; otherwise average the two tops.

Why it works

Two invariants hold after every add: every value in low is at most every value in high (because each new value passes through low and its maximum is moved across), and len(low) is len(high) or one more. Together they mean the top of low is the lower middle and the top of high is the upper middle of the sorted sequence.

Complexity

add: O(log n), a constant number of heap operations. median: O(1). Space O(n).

Code

python
import bisect
import heapq
import random


class MedianFinder:
    """Two heaps: max-heap `low` (stored negated) and min-heap `high`.
    Invariant: every value in low <= every value in high, and len(low) is len(high) or one more."""

    def __init__(self):
        self.low, self.high = [], []

    def add(self, x):                    # O(log n)
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))   # move the largest of low across
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):                    # O(1)
        if not self.low:
            raise ValueError("no values yet")
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2


class SortedListMedian:
    """Brute force reference: insert into a sorted list, O(n) per insert."""

    def __init__(self):
        self.a = []

    def add(self, x):
        bisect.insort(self.a, x)

    def median(self):
        n = len(self.a)
        return float(self.a[n // 2]) if n % 2 else (self.a[n // 2 - 1] + self.a[n // 2]) / 2


if __name__ == "__main__":
    m = MedianFinder()
    for x, want in ((1, 1.0), (2, 1.5), (3, 2.0)):
        m.add(x)
        assert m.median() == want
    try:
        MedianFinder().median()
        assert False
    except ValueError:
        pass
    rng = random.Random(61)
    for _ in range(200):
        a, b = MedianFinder(), SortedListMedian()
        for _ in range(rng.randint(1, 60)):
            x = rng.randint(-20, 20)
            a.add(x)
            b.add(x)
            assert a.median() == b.median()
    print("all tests passed")

Save as b61_median_stream.py and run python3 b61_median_stream.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty structure (raise or return None, as agreed). All values equal. Negative values with the negation trick. Even counts must return a float average.

Pattern

Two heaps that split a set at a rank. Variants: sliding-window median (add lazy deletion or use a balanced BST), IPO-style capital selection, and scheduling problems that need the best item on each side of a threshold. If values come from a small range, counting buckets make median queries O(range) with O(1) inserts.

python
import bisect
import heapq
import random


class MedianFinder:
    """Two heaps: max-heap `low` (stored negated) and min-heap `high`.
    Invariant: every value in low <= every value in high, and len(low) is len(high) or one more."""

    def __init__(self):
        self.low, self.high = [], []

    def add(self, x):                    # O(log n)
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))   # move the largest of low across
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):                    # O(1)
        if not self.low:
            raise ValueError("no values yet")
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2


class SortedListMedian:
    """Brute force reference: insert into a sorted list, O(n) per insert."""

    def __init__(self):
        self.a = []

    def add(self, x):
        bisect.insort(self.a, x)

    def median(self):
        n = len(self.a)
        return float(self.a[n // 2]) if n % 2 else (self.a[n // 2 - 1] + self.a[n // 2]) / 2


if __name__ == "__main__":
    m = MedianFinder()
    for x, want in ((1, 1.0), (2, 1.5), (3, 2.0)):
        m.add(x)
        assert m.median() == want
    try:
        MedianFinder().median()
        assert False
    except ValueError:
        pass
    rng = random.Random(61)
    for _ in range(200):
        a, b = MedianFinder(), SortedListMedian()
        for _ in range(rng.randint(1, 60)):
            x = rng.randint(-20, 20)
            a.add(x)
            b.add(x)
            assert a.median() == b.median()
    print("all tests passed")

Two-heap design with the push-through trick; random streams are checked against a sorted-list implementation after every insert.

Complexity

Time: O(log n) add, O(1) median. Space: O(n). For a bounded value range, a count array gives O(1) add and O(range) median.

By level

Fresher: Explains the sorted-list approach and then the idea of splitting values into two halves. Can trace adds with two heaps on a small example.

Mid: Implements the two heaps with correct balancing and states both invariants. Discusses the sliding-window variant and the need for deletions.

Senior: Discusses approximate quantiles at scale (t-digest, GK sketches), percentile monitoring, and merging per-shard summaries. Compares exact two-heap memory cost with sketch error bounds.

Key points

  • Max-heap for the lower half, min-heap for the upper half
  • Push through low into high, then rebalance
  • Sizes differ by at most one
  • Median from the tops
  • O(log n) add, O(1) query

Common mistakes

  • Forgetting to negate values for the max-heap in Python
  • Letting the size difference grow beyond one
  • Pushing directly into one heap without restoring the ordering invariant
  • Integer division for the even-count average

Follow-ups

  • How would you support a sliding window median?
  • What changes if 99% of values are in [0, 100]?
  • How would you approximate the median over billions of values in a distributed system?

Tips

  • State both invariants explicitly
  • Walk through three adds
  • Mention the sorted-list baseline and why it is O(n)

Evaluation rubric

  • Correct two-heap design
  • Invariants stated and maintained
  • Correct even and odd median
  • Correct complexity
62.algorithms-0062Mediumfresher

K closest points to the origin: given points on a plane, return the k nearest ones using a heap so the full list never has to be sorted.

Compare squared distances to avoid square roots. Keep a max-heap of size k (store negative distances in Python): push each point, and when the heap is full replace the top if the new point is closer. That is O(n log k) time and O(k) space. Sorting all points is O(n log n), and quickselect gives O(n) average.

Full answer

Problem

Given a list of points [x, y] and an integer k, return the k points closest to (0, 0) by Euclidean distance, in any order.

Example: points [[3, 3], [5, -1], [-2, 4]], k = 2 returns [[3, 3], [-2, 4]] (squared distances 18, 26, 20).

Constraints: 1 <= k <= n <= 10^4; coordinates from -10^4 to 10^4. The answer is unique up to ties.

Brute force

Sort all points by distance and take the first k: O(n log n) time, O(n) space for the sorted copy.

Optimal approach

Maintain a max-heap of the k best points seen so far, keyed by squared distance.

  • If the heap has fewer than k items, push.
  • Otherwise, if the new distance is smaller than the heap's maximum, replace the top (heapreplace).

At the end the heap holds the answer.

Why it works

The heap always holds the k closest points among those processed, with the farthest of them at the top. A new point belongs in the answer exactly when it is closer than that farthest one, and then the farthest one is the point that drops out. Squared distance preserves order because squaring is monotonic for non-negative values.

Complexity

O(n log k) time, O(k) space. Quickselect (partition around a pivot until index k) is O(n) average and O(n^2) worst case, and it rearranges the input.

Code

python
import heapq
import random


def k_closest(points, k):
    """Keep a max-heap of size k keyed by -distance. O(n log k) time, O(k) space."""
    heap = []
    for x, y in points:
        d = x * x + y * y                # squared distance: no sqrt needed to compare
        if len(heap) < k:
            heapq.heappush(heap, (-d, x, y))
        elif -heap[0][0] > d:
            heapq.heapreplace(heap, (-d, x, y))
    return [[x, y] for _, x, y in heap]


def brute(points, k):
    """Sort everything: O(n log n)."""
    return sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2)[:k]


def dists(pts):
    return sorted(x * x + y * y for x, y in pts)


if __name__ == "__main__":
    assert sorted(k_closest([[1, 3], [-2, 2]], 1)) == [[-2, 2]]
    assert sorted(k_closest([[3, 3], [5, -1], [-2, 4]], 2)) == [[-2, 4], [3, 3]]
    assert k_closest([[0, 0]], 1) == [[0, 0]]
    rng = random.Random(62)
    for _ in range(1000):
        pts = [[rng.randint(-10, 10), rng.randint(-10, 10)] for _ in range(rng.randint(1, 30))]
        k = rng.randint(1, len(pts))
        got = k_closest(pts, k)
        assert len(got) == k and dists(got) == dists(brute(pts, k))   # ties may pick different points
    print("all tests passed")

Save as b62_k_closest.py and run python3 b62_k_closest.py. It prints all tests passed (Python 3.13.5).

Edge cases

k equals n (return all). Ties in distance (any valid set is accepted; tests compare distances). Duplicate points. Points at the origin. Large coordinates: squared values fit easily in Python ints; in 32-bit languages, use 64-bit integers.

Pattern

Bounded heap for top-k: keep the k best in a heap ordered by the worst of them. The same pattern gives kth largest in a stream, top-k frequent words, and nearest neighbours in a streaming feed. When the data fits in memory and order does not matter, quickselect is the alternative.

python
import heapq
import random


def k_closest(points, k):
    """Keep a max-heap of size k keyed by -distance. O(n log k) time, O(k) space."""
    heap = []
    for x, y in points:
        d = x * x + y * y                # squared distance: no sqrt needed to compare
        if len(heap) < k:
            heapq.heappush(heap, (-d, x, y))
        elif -heap[0][0] > d:
            heapq.heapreplace(heap, (-d, x, y))
    return [[x, y] for _, x, y in heap]


def brute(points, k):
    """Sort everything: O(n log n)."""
    return sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2)[:k]


def dists(pts):
    return sorted(x * x + y * y for x, y in pts)


if __name__ == "__main__":
    assert sorted(k_closest([[1, 3], [-2, 2]], 1)) == [[-2, 2]]
    assert sorted(k_closest([[3, 3], [5, -1], [-2, 4]], 2)) == [[-2, 4], [3, 3]]
    assert k_closest([[0, 0]], 1) == [[0, 0]]
    rng = random.Random(62)
    for _ in range(1000):
        pts = [[rng.randint(-10, 10), rng.randint(-10, 10)] for _ in range(rng.randint(1, 30))]
        k = rng.randint(1, len(pts))
        got = k_closest(pts, k)
        assert len(got) == k and dists(got) == dists(brute(pts, k))   # ties may pick different points
    print("all tests passed")

Size-k max-heap with squared distances, checked against full sorting on random inputs by comparing the multiset of distances.

Complexity

Time: O(n log k). Space: O(k). Quickselect is O(n) average; sorting is O(n log n).

By level

Fresher: Sorts by squared distance as a first answer, then explains the size-k heap and when the top is replaced. States the time complexity of each.

Mid: Implements the bounded heap correctly and compares it with quickselect on time, memory and input mutation. Handles streaming input.

Senior: Discusses spatial indexes such as k-d trees, geohash cells and approximate nearest neighbour indexes for repeated queries. Weighs exactness against latency for large-scale proximity search.

Key points

  • Use squared distance
  • Max-heap of size k holds the current best
  • Replace the top only when the new point is closer
  • O(n log k) beats O(n log n) for small k
  • Quickselect is the O(n) average alternative

Common mistakes

  • Using a min-heap of all n points and popping k (O(n + k log n), fine, but not the bounded version asked)
  • Computing sqrt needlessly
  • Forgetting to negate for a max-heap in Python
  • Assuming a unique answer when ties exist

Follow-ups

  • How would you handle a stream of points where k stays fixed?
  • When is quickselect better than a heap?
  • How would you find k nearest neighbours to an arbitrary query point many times (k-d tree)?

Tips

  • Mention squared distance early
  • State why the heap holds the farthest of the best at the top
  • Offer quickselect as an alternative

Evaluation rubric

  • Correct bounded-heap logic
  • Correct complexity
  • Handles ties
  • Knows the quickselect option
63.algorithms-0063Mediummid

Reorganize a string so that no two adjacent characters are the same, or report that it is impossible, using a greedy heap strategy.

It is impossible exactly when the most frequent character appears more than (n + 1) // 2 times. Otherwise, repeatedly take the most frequent character that differs from the one just placed, using a max-heap and holding the last-used character out for one step. That is O(n log A) time, where A is the alphabet size, and O(A) heap space.

Full answer

Problem

Given a string s, rearrange its characters so that no two adjacent characters are equal. Return any valid arrangement, or "" if none exists.

Example: "aab" becomes "aba"; "aaab" returns "".

Constraints: 1 <= len(s) <= 500, lowercase letters.

Brute force

Try permutations until one has no equal neighbours: O(n!) and only usable for tiny inputs (the tests use it as a reference for strings up to 7 characters).

Optimal approach

  1. Count characters. If the top count exceeds (n + 1) // 2, return "".
  2. Push (-count, char) for each character into a heap.
  3. Loop: pop the most frequent character, append it, then push back the character held from the previous step (if it still has copies). Hold the current one (with its count reduced) for the next step.

The held character cannot be chosen twice in a row because it is outside the heap during the next pick.

Why it works

Placing the most frequent available character first is the safe choice: the risk of failure comes from the character with the most copies left, and using it as often as allowed spreads it out. The counting bound is necessary because in n positions with no two neighbours equal, one character can fill at most every other slot, which is (n + 1) // 2 slots. When the bound holds, the greedy never gets stuck, which the random cross-check confirms against exhaustive search.

Complexity

O(n log A) time where A is the number of distinct characters (at most 26 here, so effectively O(n)). O(A) space for the heap and counts, plus the output.

Code

python
import heapq
import random
from collections import Counter
from itertools import permutations


def reorganize(s):
    """Rearrange so no two adjacent characters match, or return ''.
    Greedy with a max-heap: always place the most frequent character that differs from the last one."""
    counts = Counter(s)
    if counts and max(counts.values()) > (len(s) + 1) // 2:
        return ""                        # impossible: the top character cannot be separated
    heap = [(-c, ch) for ch, c in counts.items()]
    heapq.heapify(heap)
    out, held = [], None                 # held: the character used last step, waiting one turn
    while heap:
        c, ch = heapq.heappop(heap)
        out.append(ch)
        if held:
            heapq.heappush(heap, held)
        held = (c + 1, ch) if c + 1 < 0 else None
    return "".join(out)


def valid(s, t):
    return sorted(s) == sorted(t) and all(a != b for a, b in zip(t, t[1:]))


def brute_possible(s):
    return any(valid(s, "".join(p)) for p in set(permutations(s)))


if __name__ == "__main__":
    assert valid("aab", reorganize("aab"))
    assert reorganize("aaab") == ""
    assert reorganize("") == "" and reorganize("a") == "a"
    assert valid("aaabbc", reorganize("aaabbc"))
    rng = random.Random(63)
    for _ in range(600):
        s = "".join(rng.choice("aabbc") for _ in range(rng.randint(1, 7)))
        got = reorganize(s)
        assert (got != "") == brute_possible(s)
        if got:
            assert valid(s, got)
    print("all tests passed")

Save as b63_reorganize_string.py and run python3 b63_reorganize_string.py. It prints all tests passed (Python 3.13.5).

Edge cases

Single character string. All characters the same (only valid if length 1). Exactly (n + 1) // 2 copies of one character (valid, it fills every other slot). Empty string returns "".

Pattern

Greedy scheduling with a max-heap and a cooldown. The task scheduler problem (identical tasks must be k slots apart) uses the same loop with a queue of cooling items, and "distant barcodes" is the same problem on integers. An alternative O(n) method fills even indices first with the most frequent character, then the rest.

python
import heapq
import random
from collections import Counter
from itertools import permutations


def reorganize(s):
    """Rearrange so no two adjacent characters match, or return ''.
    Greedy with a max-heap: always place the most frequent character that differs from the last one."""
    counts = Counter(s)
    if counts and max(counts.values()) > (len(s) + 1) // 2:
        return ""                        # impossible: the top character cannot be separated
    heap = [(-c, ch) for ch, c in counts.items()]
    heapq.heapify(heap)
    out, held = [], None                 # held: the character used last step, waiting one turn
    while heap:
        c, ch = heapq.heappop(heap)
        out.append(ch)
        if held:
            heapq.heappush(heap, held)
        held = (c + 1, ch) if c + 1 < 0 else None
    return "".join(out)


def valid(s, t):
    return sorted(s) == sorted(t) and all(a != b for a, b in zip(t, t[1:]))


def brute_possible(s):
    return any(valid(s, "".join(p)) for p in set(permutations(s)))


if __name__ == "__main__":
    assert valid("aab", reorganize("aab"))
    assert reorganize("aaab") == ""
    assert reorganize("") == "" and reorganize("a") == "a"
    assert valid("aaabbc", reorganize("aaabbc"))
    rng = random.Random(63)
    for _ in range(600):
        s = "".join(rng.choice("aabbc") for _ in range(rng.randint(1, 7)))
        got = reorganize(s)
        assert (got != "") == brute_possible(s)
        if got:
            assert valid(s, got)
    print("all tests passed")

Feasibility bound, heap with a one-step hold, and an exhaustive permutation reference for short strings.

Complexity

Time: O(n log A). Space: O(A). With a fixed 26-letter alphabet this is effectively O(n); the even-index filling method is O(n) without a heap.

By level

Fresher: Derives the (n + 1) // 2 bound by thinking about every other slot. Follows the heap-based greedy step by step on a small input.

Mid: Implements the heap loop with the hold step and handles the impossible case. Extends it to the k-apart task scheduler with a cooldown queue.

Senior: Proves or argues why the greedy cannot get stuck when the bound holds, and presents the O(n) even-index filling method. Relates the pattern to rate-limited job scheduling and fair interleaving of tenants.

Key points

  • Impossible when max count > (n + 1) // 2
  • Always place the most frequent allowed character
  • Hold the last character out for one step
  • Heap of (-count, char)
  • Same skeleton as task scheduler

Common mistakes

  • Pushing the just-used character back immediately so it can repeat
  • Using the bound n // 2 instead of (n + 1) // 2
  • Forgetting characters whose count reaches zero
  • Not handling the impossible case before looping

Follow-ups

  • How does this change if equal characters must be at least k apart?
  • Can you solve it in O(n) without a heap?
  • How would you minimize idle slots in the task scheduler version?

Tips

  • State the feasibility bound first
  • Explain why the held character cannot repeat
  • Relate to the task scheduler

Evaluation rubric

  • Correct impossibility check
  • Valid output for possible inputs
  • Correct complexity
  • Explains the greedy choice
64.algorithms-0064Easyfresher

Represent a graph in code: build an adjacency list from an edge list, compare it with an adjacency matrix, and compute degrees.

An adjacency list stores, for every node, the list of its neighbours: O(V + E) space and neighbour iteration in O(degree). An adjacency matrix uses O(V^2) space but answers "is there an edge u-v" in O(1). For undirected graphs add each edge in both directions; for weighted graphs store (neighbour, weight) pairs. Most interview graphs are sparse, so the list is the default.

Full answer

Problem

Given n nodes labelled 0..n-1 and a list of edges, build a structure that lets algorithms iterate over each node's neighbours. Support directed, undirected and weighted edges, and compute degrees.

Example: n = 4, edges [(0, 1), (0, 2), (1, 2), (2, 3)] undirected gives [[1, 2], [0, 2], [0, 1, 3], [2]] and degrees [2, 2, 3, 1].

Constraints: up to 10^5 nodes and 2 * 10^5 edges, so the representation must be close to linear in size.

Brute force

Keep only the raw edge list. Finding the neighbours of one node scans all E edges, so a BFS or DFS becomes O(V * E).

Optimal approach

Adjacency list: adj = [[] for _ in range(n)]; for each (u, v) append v to adj[u] and, if undirected, u to adj[v]. For labels that are strings or sparse ids, use defaultdict(list). For weights, append (v, w).

Adjacency matrix: an n x n grid of 0/1 (or weights). Use it when the graph is small and dense or when edge-existence tests dominate.

Why it works

Graph algorithms mostly ask "who are the neighbours of u". The adjacency list answers that by indexing once and iterating exactly deg(u) entries, so a full traversal touches each edge a constant number of times. The sum of all degrees in an undirected graph is 2E (each edge is stored twice), which is why space is O(V + E).

Complexity

ListMatrix
SpaceO(V + E)O(V^2)
Neighbours of uO(deg u)O(V)
Edge test u-vO(deg u), or O(1) with setsO(1)
BuildO(V + E)O(V^2)

Code

python
from collections import defaultdict


def build_adjacency(n, edges, directed=False):
    """Adjacency list as a list of lists. O(V + E) space; neighbours of u in O(deg(u))."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)
    return adj


def build_weighted(edges, directed=True):
    """Dict of lists for sparse or non-integer node ids: {u: [(v, w), ...]}."""
    adj = defaultdict(list)
    for u, v, w in edges:
        adj[u].append((v, w))
        if not directed:
            adj[v].append((u, w))
    return adj


def build_matrix(n, edges, directed=False):
    """Adjacency matrix: O(V^2) space, O(1) edge test. Fine for small dense graphs."""
    m = [[0] * n for _ in range(n)]
    for u, v in edges:
        m[u][v] = 1
        if not directed:
            m[v][u] = 1
    return m


def degrees(adj):
    return [len(nbrs) for nbrs in adj]


def in_degrees(n, adj):
    indeg = [0] * n
    for u in range(n):
        for v in adj[u]:
            indeg[v] += 1
    return indeg


if __name__ == "__main__":
    edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
    adj = build_adjacency(4, edges)
    assert adj == [[1, 2], [0, 2], [0, 1, 3], [2]]
    assert degrees(adj) == [2, 2, 3, 1]
    assert sum(degrees(adj)) == 2 * len(edges)            # handshake lemma
    dadj = build_adjacency(4, edges, directed=True)
    assert dadj == [[1, 2], [2], [3], []]
    assert in_degrees(4, dadj) == [0, 1, 2, 1]
    m = build_matrix(4, edges)
    assert all(m[u][v] == (v in adj[u]) for u in range(4) for v in range(4))
    w = build_weighted([("a", "b", 5), ("b", "c", 2)])
    assert w["a"] == [("b", 5)] and w["c"] == []
    assert build_adjacency(3, []) == [[], [], []]         # isolated nodes still get a list
    print("all tests passed")

Save as b64_adjacency_list.py and run python3 b64_adjacency_list.py. It prints all tests passed (Python 3.13.5).

Edge cases

Isolated nodes (still need an empty list, or a later lookup fails). Self-loops (appear once or twice depending on the convention; agree on it). Parallel edges (lists keep both; sets merge them). 1-indexed input (allocate n + 1 or shift labels).

Pattern

Choosing the graph representation before writing the algorithm. Lists suit BFS, DFS, Dijkstra and topological sort; matrices suit Floyd-Warshall and dense bitset tricks; edge lists suit Kruskal and Bellman-Ford. Grids are implicit graphs where neighbours are computed from coordinates.

python
from collections import defaultdict


def build_adjacency(n, edges, directed=False):
    """Adjacency list as a list of lists. O(V + E) space; neighbours of u in O(deg(u))."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)
    return adj


def build_weighted(edges, directed=True):
    """Dict of lists for sparse or non-integer node ids: {u: [(v, w), ...]}."""
    adj = defaultdict(list)
    for u, v, w in edges:
        adj[u].append((v, w))
        if not directed:
            adj[v].append((u, w))
    return adj


def build_matrix(n, edges, directed=False):
    """Adjacency matrix: O(V^2) space, O(1) edge test. Fine for small dense graphs."""
    m = [[0] * n for _ in range(n)]
    for u, v in edges:
        m[u][v] = 1
        if not directed:
            m[v][u] = 1
    return m


def degrees(adj):
    return [len(nbrs) for nbrs in adj]


def in_degrees(n, adj):
    indeg = [0] * n
    for u in range(n):
        for v in adj[u]:
            indeg[v] += 1
    return indeg


if __name__ == "__main__":
    edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
    adj = build_adjacency(4, edges)
    assert adj == [[1, 2], [0, 2], [0, 1, 3], [2]]
    assert degrees(adj) == [2, 2, 3, 1]
    assert sum(degrees(adj)) == 2 * len(edges)            # handshake lemma
    dadj = build_adjacency(4, edges, directed=True)
    assert dadj == [[1, 2], [2], [3], []]
    assert in_degrees(4, dadj) == [0, 1, 2, 1]
    m = build_matrix(4, edges)
    assert all(m[u][v] == (v in adj[u]) for u in range(4) for v in range(4))
    w = build_weighted([("a", "b", 5), ("b", "c", 2)])
    assert w["a"] == [("b", 5)] and w["c"] == []
    assert build_adjacency(3, []) == [[], [], []]         # isolated nodes still get a list
    print("all tests passed")

List-of-lists, dict-of-lists with weights, and matrix builders, plus degree and in-degree helpers checked with the handshake lemma.

Complexity

Time: O(V + E) build. Space: O(V + E) list, O(V^2) matrix. Use a set per node when fast edge tests are needed in a sparse graph.

By level

Fresher: Builds an adjacency list from an edge list for both directed and undirected graphs. Explains why a matrix is a poor choice for a large sparse graph.

Mid: Compares list, matrix and edge-list representations against the algorithm that will use them. Handles weights, string labels and in-degree computation.

Senior: Discusses CSR arrays for cache-friendly traversal, sharded adjacency storage for very large graphs, and the cost of edge-existence checks at scale. Chooses representations based on the read and update pattern.

Key points

  • Adjacency list is O(V + E) space
  • Undirected edges are stored twice
  • Matrix gives O(1) edge tests at O(V^2) space
  • Weighted edges store (neighbour, weight)
  • Isolated nodes still need entries

Common mistakes

  • Forgetting the reverse edge for undirected graphs
  • Using a matrix for 10^5 nodes
  • Missing isolated nodes in a dict-based list
  • Mixing 0-indexed and 1-indexed labels

Follow-ups

  • How would you store a graph with 10^9 edges that does not fit in memory?
  • What is compressed sparse row (CSR) format?
  • How do you represent a grid as a graph without building edges?

Tips

  • Ask whether the graph is directed and weighted
  • State V and E sizes to justify the choice
  • Mention the handshake lemma for degree sums

Evaluation rubric

  • Correct construction for directed and undirected
  • Correct complexity comparison
  • Handles isolated nodes
  • Justifies the choice
65.algorithms-0065Easyfresher

Depth-first search on a graph: visit every node reachable from a start node, recursively and with an explicit stack, and count connected components.

DFS follows one neighbour as deep as possible before backtracking. Mark a node visited when it is first reached so cycles do not loop forever. Recursive and stack-based versions both run in O(V + E) time and O(V) space; the stack version avoids recursion limits. Starting a new DFS from each unvisited node counts connected components.

Full answer

Problem

Given an undirected graph as an adjacency list and a start node, return the nodes in DFS visiting order. Also count the connected components of the whole graph.

Example: {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2], 4: []} from 0 visits [0, 1, 3, 2], and the graph has 2 components ({0, 1, 2, 3} and {4}).

Constraints: up to 10^5 nodes and edges; the graph may contain cycles and isolated nodes.

Brute force

Without a visited set, a recursive walk revisits nodes through every cycle and never terminates. Checking "visited" by scanning the output list works but costs O(V) per check, giving O(V^2 + E).

Optimal approach

Recursive: visit(u) marks u, records it, and calls visit(v) for each unvisited neighbour.

Iterative: push the start; pop u; skip if already seen; mark and record; push unvisited neighbours in reverse so the order matches the recursive version.

Components: loop over all nodes; each unvisited node starts a new DFS and increments the count.

Why it works

Every reachable node is eventually pushed, because DFS explores every edge out of every visited node. The visited set guarantees each node is processed once, so cycles terminate. In the component loop, one DFS marks exactly the nodes connected to its start, so each new start belongs to a component not yet counted.

Complexity

O(V + E) time: each node is processed once and each adjacency list scanned once. O(V) space for the visited set and the stack (or recursion depth).

Code

python
import random


def dfs_recursive(adj, start):
    order, seen = [], set()

    def visit(u):
        seen.add(u)                      # mark on entry so cycles terminate
        order.append(u)
        for v in adj[u]:
            if v not in seen:
                visit(v)
    visit(start)
    return order


def dfs_iterative(adj, start):
    """Explicit stack. Neighbours pushed in reverse so the visit order matches the recursive one."""
    order, seen, stack = [], set(), [start]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        for v in reversed(adj[u]):
            if v not in seen:
                stack.append(v)
    return order


def count_components(n, adj):
    seen, comps = set(), 0
    for s in range(n):
        if s not in seen:
            comps += 1
            stack = [s]
            seen.add(s)
            while stack:
                u = stack.pop()
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        stack.append(v)
    return comps


def has_path(adj, a, b):
    return b in set(dfs_iterative(adj, a))


def brute_components(n, edges):
    """Repeatedly merge labels until nothing changes."""
    label = list(range(n))
    changed = True
    while changed:
        changed = False
        for u, v in edges:
            m = min(label[u], label[v])
            if label[u] != m or label[v] != m:
                label[u] = label[v] = m
                changed = True
    return len(set(label))


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2], 4: []}
    assert dfs_recursive(adj, 0) == dfs_iterative(adj, 0) == [0, 1, 3, 2]
    assert dfs_iterative(adj, 4) == [4]
    assert has_path(adj, 0, 3) and not has_path(adj, 0, 4)
    assert count_components(5, adj) == 2
    rng = random.Random(65)
    for _ in range(500):
        n = rng.randint(1, 12)
        edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 15))]
        g = {u: [] for u in range(n)}
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        assert count_components(n, g) == brute_components(n, edges)
        assert dfs_recursive(g, 0) == dfs_iterative(g, 0)
    print("all tests passed")

Save as b65_dfs.py and run python3 b65_dfs.py. It prints all tests passed (Python 3.13.5).

Edge cases

Start node with no edges. Self-loops and parallel edges. Disconnected graphs (single-start DFS misses other components). Deep paths with 10^5 nodes overflow Python's recursion limit, so use the stack version.

Pattern

Graph traversal with a visited set. DFS underlies connected components, cycle detection, topological sort, flood fill, path existence, bridges and articulation points, and backtracking over implicit graphs.

python
import random


def dfs_recursive(adj, start):
    order, seen = [], set()

    def visit(u):
        seen.add(u)                      # mark on entry so cycles terminate
        order.append(u)
        for v in adj[u]:
            if v not in seen:
                visit(v)
    visit(start)
    return order


def dfs_iterative(adj, start):
    """Explicit stack. Neighbours pushed in reverse so the visit order matches the recursive one."""
    order, seen, stack = [], set(), [start]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        for v in reversed(adj[u]):
            if v not in seen:
                stack.append(v)
    return order


def count_components(n, adj):
    seen, comps = set(), 0
    for s in range(n):
        if s not in seen:
            comps += 1
            stack = [s]
            seen.add(s)
            while stack:
                u = stack.pop()
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        stack.append(v)
    return comps


def has_path(adj, a, b):
    return b in set(dfs_iterative(adj, a))


def brute_components(n, edges):
    """Repeatedly merge labels until nothing changes."""
    label = list(range(n))
    changed = True
    while changed:
        changed = False
        for u, v in edges:
            m = min(label[u], label[v])
            if label[u] != m or label[v] != m:
                label[u] = label[v] = m
                changed = True
    return len(set(label))


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2], 4: []}
    assert dfs_recursive(adj, 0) == dfs_iterative(adj, 0) == [0, 1, 3, 2]
    assert dfs_iterative(adj, 4) == [4]
    assert has_path(adj, 0, 3) and not has_path(adj, 0, 4)
    assert count_components(5, adj) == 2
    rng = random.Random(65)
    for _ in range(500):
        n = rng.randint(1, 12)
        edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 15))]
        g = {u: [] for u in range(n)}
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        assert count_components(n, g) == brute_components(n, edges)
        assert dfs_recursive(g, 0) == dfs_iterative(g, 0)
    print("all tests passed")

Recursive and stack DFS with matching order, plus component counting cross-checked against a label-merging brute force.

Complexity

Time: O(V + E). Space: O(V). The iterative version may push a node several times before it is popped; the seen check on pop keeps processing to once per node.

By level

Fresher: Writes recursive DFS with a visited set and explains why cycles would otherwise loop. Counts components by starting DFS from each unvisited node.

Mid: Writes the stack version, explains marking on push versus pop, and states O(V + E). Uses DFS to find a path and to check reachability.

Senior: Discusses DFS on implicit or very large graphs, iterative deepening, and memory limits of the visited set. Relates DFS orderings (pre and post times) to cycle detection, topological sort and strongly connected components.

Key points

  • Mark visited to handle cycles
  • Recursive and stack versions are equivalent
  • Push neighbours in reverse to match recursive order
  • One DFS per unvisited node counts components
  • O(V + E)

Common mistakes

  • Marking visited too late and processing a node twice
  • No visited set at all on a cyclic graph
  • Using recursion on very deep graphs in Python
  • Only searching from one start on a disconnected graph

Follow-ups

  • How do you detect a cycle with DFS?
  • How would you find a path, not just reachability?
  • When would you prefer BFS over DFS?

Tips

  • Say where the visited mark happens
  • Mention recursion limits
  • Connect DFS to components and topological sort

Evaluation rubric

  • Correct traversal with visited set
  • Iterative version
  • Component count
  • Correct complexity
66.algorithms-0066Easyfresher

Breadth-first search for shortest paths in an unweighted graph: compute distances from a source and rebuild one shortest path to a target.

BFS explores nodes in rings of increasing distance using a FIFO queue. Mark a node when it is enqueued and set its distance to the parent's plus one; the first time a node is reached is via a shortest path. Storing a parent pointer per node lets the path be rebuilt by walking back from the target. Time O(V + E), space O(V).

Full answer

Problem

Given a directed or undirected unweighted graph and a source s, return the fewest-edge distance from s to every reachable node, and one shortest path from s to a target t.

Example: {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [], 5: [0]} from 0 gives distances {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}; one shortest path to 4 is [0, 1, 3, 4]; node 5 is unreachable from 0.

Constraints: up to 10^5 nodes and edges.

Brute force

DFS over all simple paths and keep the shortest: exponential in the worst case. Repeated relaxation of all edges (Bellman-Ford with unit weights) is polynomial but O(V * E).

Optimal approach

  1. dist = {s: 0}, queue [s].
  2. Pop u from the front. For each neighbour v not in dist, set dist[v] = dist[u] + 1, parent[v] = u, and enqueue v.
  3. To rebuild the path to t, follow parent from t back to s and reverse.

Why it works

The queue always contains nodes at distance d followed by nodes at distance d + 1, never further. So nodes are dequeued in non-decreasing distance order, and the first time a node is discovered, it is from a node one step closer to s than any other discoverer could be. Marking on enqueue (not on dequeue) prevents a node from being queued twice with a worse distance.

Complexity

O(V + E) time, O(V) space for the queue, distances and parents.

Code

python
import random
from collections import deque


def bfs_distances(adj, start):
    """Fewest edges from start to every reachable node. O(V + E)."""
    dist = {start: 0}
    q = deque([start])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in dist:            # mark when enqueued, not when dequeued
                dist[v] = dist[u] + 1
                q.append(v)
    return dist


def shortest_path(adj, start, goal):
    """Return one shortest path as a list of nodes, or [] if unreachable."""
    parent = {start: None}
    q = deque([start])
    while q:
        u = q.popleft()
        if u == goal:
            path = []
            while u is not None:
                path.append(u)
                u = parent[u]
            return path[::-1]
        for v in adj[u]:
            if v not in parent:
                parent[v] = u
                q.append(v)
    return []


def brute_dist(n, adj, s):
    """Bellman-Ford style relaxation with unit weights: O(V * E)."""
    INF = float("inf")
    d = [INF] * n
    d[s] = 0
    for _ in range(n):
        for u in range(n):
            for v in adj[u]:
                d[v] = min(d[v], d[u] + 1)
    return {u: d[u] for u in range(n) if d[u] < INF}


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [], 5: [0]}
    assert bfs_distances(adj, 0) == {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
    assert shortest_path(adj, 0, 4) == [0, 1, 3, 4]
    assert shortest_path(adj, 0, 5) == []
    assert shortest_path(adj, 2, 2) == [2]
    rng = random.Random(66)
    for _ in range(500):
        n = rng.randint(1, 10)
        g = {u: [] for u in range(n)}
        for _ in range(rng.randint(0, 20)):
            g[rng.randrange(n)].append(rng.randrange(n))
        s = rng.randrange(n)
        d = bfs_distances(g, s)
        assert d == brute_dist(n, g, s)
        t = rng.randrange(n)
        p = shortest_path(g, s, t)
        assert (len(p) - 1 if p else None) == d.get(t)
    print("all tests passed")

Save as b66_bfs.py and run python3 b66_bfs.py. It prints all tests passed (Python 3.13.5).

Edge cases

Source equals target (path [s]). Unreachable target (return [] or -1). Directed edges that only go one way. Weighted graphs: BFS is wrong once weights differ; use 0-1 BFS for weights 0 and 1, Dijkstra for non-negative weights.

Pattern

Level-order exploration for unweighted shortest paths. It covers grid mazes, word ladder (implicit graph of one-letter changes), multi-source BFS (rotting oranges, distance to nearest exit), and state-space search where each move costs 1.

python
import random
from collections import deque


def bfs_distances(adj, start):
    """Fewest edges from start to every reachable node. O(V + E)."""
    dist = {start: 0}
    q = deque([start])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in dist:            # mark when enqueued, not when dequeued
                dist[v] = dist[u] + 1
                q.append(v)
    return dist


def shortest_path(adj, start, goal):
    """Return one shortest path as a list of nodes, or [] if unreachable."""
    parent = {start: None}
    q = deque([start])
    while q:
        u = q.popleft()
        if u == goal:
            path = []
            while u is not None:
                path.append(u)
                u = parent[u]
            return path[::-1]
        for v in adj[u]:
            if v not in parent:
                parent[v] = u
                q.append(v)
    return []


def brute_dist(n, adj, s):
    """Bellman-Ford style relaxation with unit weights: O(V * E)."""
    INF = float("inf")
    d = [INF] * n
    d[s] = 0
    for _ in range(n):
        for u in range(n):
            for v in adj[u]:
                d[v] = min(d[v], d[u] + 1)
    return {u: d[u] for u in range(n) if d[u] < INF}


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [], 5: [0]}
    assert bfs_distances(adj, 0) == {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
    assert shortest_path(adj, 0, 4) == [0, 1, 3, 4]
    assert shortest_path(adj, 0, 5) == []
    assert shortest_path(adj, 2, 2) == [2]
    rng = random.Random(66)
    for _ in range(500):
        n = rng.randint(1, 10)
        g = {u: [] for u in range(n)}
        for _ in range(rng.randint(0, 20)):
            g[rng.randrange(n)].append(rng.randrange(n))
        s = rng.randrange(n)
        d = bfs_distances(g, s)
        assert d == brute_dist(n, g, s)
        t = rng.randrange(n)
        p = shortest_path(g, s, t)
        assert (len(p) - 1 if p else None) == d.get(t)
    print("all tests passed")

Distances and parent-pointer path reconstruction, checked against unit-weight relaxation on random directed graphs.

Complexity

Time: O(V + E). Space: O(V). Stopping as soon as the target is dequeued saves time but not the worst-case bound.

By level

Fresher: Writes BFS with a deque and a distance map, and traces it on a small graph. Rebuilds a path using parent pointers.

Mid: Explains the queue invariant that makes BFS correct and the effect of marking on enqueue. Applies BFS to grids and implicit graphs.

Senior: Discusses bidirectional BFS and its effect on explored nodes, BFS on graphs that do not fit in memory, and frontier-based parallel BFS. Chooses between BFS, 0-1 BFS and Dijkstra based on the weights.

Key points

  • FIFO queue gives non-decreasing distance order
  • Mark when enqueued
  • dist[v] = dist[u] + 1 on discovery
  • Parent pointers rebuild the path
  • Only valid for unweighted (or equal-weight) edges

Common mistakes

  • Marking visited on dequeue, causing duplicate enqueues
  • Using a list with pop(0)
  • Using BFS on weighted graphs
  • Forgetting the unreachable case

Follow-ups

  • How would you search from both ends (bidirectional BFS)?
  • How do you find shortest distances from several sources at once?
  • What changes when edges have weight 0 or 1?

Tips

  • State the queue invariant
  • Mention marking on enqueue
  • Explain when BFS stops being correct

Evaluation rubric

  • Correct BFS with distances
  • Path reconstruction
  • Correct complexity
  • Knows limits on weighted graphs
67.algorithms-0067Mediumfresher

Number of islands: count groups of land cells connected horizontally or vertically in a grid of '1' (land) and '0' (water).

Scan every cell; when an unvisited land cell is found, increment the count and flood-fill its whole island with BFS or DFS so it is not counted again. Each cell is visited a constant number of times, giving O(R * C) time. Union-find is an alternative that also handles land being added over time.

Full answer

Problem

Given an R x C grid of '1' and '0', return the number of islands. An island is a maximal group of land cells connected up, down, left or right (not diagonally).

Example:

11000 11000 00100 00011

has 3 islands.

Constraints: 1 <= R, C <= 300.

Brute force

For every land cell, run a fresh search to collect its island, then deduplicate islands by comparing cell sets. Repeated searches make this O((R * C)^2) in the worst case.

Optimal approach

Flood fill:

  1. Copy the grid (or keep a visited set) so the input is not modified.
  2. For each cell that is '1': count += 1, mark it '0', and BFS through its land neighbours, marking each when it is enqueued.

Union-find alternative: create a set per land cell and union each with its land neighbours above and to the left; the answer is the number of distinct roots.

Why it works

The grid is a graph whose nodes are land cells and whose edges join 4-adjacent land cells; an island is a connected component. Each flood fill marks one entire component, so every later scan step that finds unmarked land is in a new component.

Complexity

O(R * C) time: each cell is examined by the scan and enqueued at most once. Space O(R * C) for the copy, plus O(min(R, C)) to O(R * C) for the BFS queue. Recursive DFS can reach depth R * C on a snake-shaped island, which exceeds Python's recursion limit, so BFS or an explicit stack is safer.

Code

python
import random
from collections import deque


def num_islands(grid):
    """Count 4-connected groups of '1'. BFS flood fill, O(R * C) time.
    Works on a copy so the caller's grid is not modified."""
    if not grid:
        return 0
    g = [row[:] for row in grid]
    rows, cols, count = len(g), len(g[0]), 0
    for r in range(rows):
        for c in range(cols):
            if g[r][c] != "1":
                continue
            count += 1
            g[r][c] = "0"                # sink on enqueue so no cell is queued twice
            q = deque([(r, c)])
            while q:
                y, x = q.popleft()
                for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                    if 0 <= ny < rows and 0 <= nx < cols and g[ny][nx] == "1":
                        g[ny][nx] = "0"
                        q.append((ny, nx))
    return count


def num_islands_uf(grid):
    """Union-find version: useful when land is added cell by cell."""
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    parent = {}

    def find(a):
        while parent[a] != a:
            parent[a] = parent[parent[a]]
            a = parent[a]
        return a
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                parent[(r, c)] = (r, c)
                for p in ((r - 1, c), (r, c - 1)):
                    if p in parent:
                        parent[find(p)] = find((r, c))
    return len({find(p) for p in parent})


if __name__ == "__main__":
    grid = [list("11000"), list("11000"), list("00100"), list("00011")]
    assert num_islands(grid) == num_islands_uf(grid) == 3
    assert grid[0][0] == "1"                              # input untouched
    assert num_islands([]) == 0 and num_islands([list("0")]) == 0
    assert num_islands([list("101"), list("010"), list("101")]) == 5   # diagonals do not connect
    rng = random.Random(67)
    for _ in range(500):
        r, c = rng.randint(1, 8), rng.randint(1, 8)
        g = [[rng.choice("01") for _ in range(c)] for _ in range(r)]
        assert num_islands(g) == num_islands_uf(g)
    print("all tests passed")

Save as b67_islands.py and run python3 b67_islands.py. It prints all tests passed (Python 3.13.5).

Edge cases

All water (0). All land (1). Diagonal touching does not connect (the checkerboard test has 5 islands). Single row or column. Mutating the caller's grid is often unacceptable; say whether the input may be modified.

Pattern

Connected components on a grid via flood fill. Related problems: max area of island, surrounded regions, number of distinct island shapes (record the path signature), and "number of islands II" where cells turn to land one by one, which needs union-find.

python
import random
from collections import deque


def num_islands(grid):
    """Count 4-connected groups of '1'. BFS flood fill, O(R * C) time.
    Works on a copy so the caller's grid is not modified."""
    if not grid:
        return 0
    g = [row[:] for row in grid]
    rows, cols, count = len(g), len(g[0]), 0
    for r in range(rows):
        for c in range(cols):
            if g[r][c] != "1":
                continue
            count += 1
            g[r][c] = "0"                # sink on enqueue so no cell is queued twice
            q = deque([(r, c)])
            while q:
                y, x = q.popleft()
                for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                    if 0 <= ny < rows and 0 <= nx < cols and g[ny][nx] == "1":
                        g[ny][nx] = "0"
                        q.append((ny, nx))
    return count


def num_islands_uf(grid):
    """Union-find version: useful when land is added cell by cell."""
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    parent = {}

    def find(a):
        while parent[a] != a:
            parent[a] = parent[parent[a]]
            a = parent[a]
        return a
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                parent[(r, c)] = (r, c)
                for p in ((r - 1, c), (r, c - 1)):
                    if p in parent:
                        parent[find(p)] = find((r, c))
    return len({find(p) for p in parent})


if __name__ == "__main__":
    grid = [list("11000"), list("11000"), list("00100"), list("00011")]
    assert num_islands(grid) == num_islands_uf(grid) == 3
    assert grid[0][0] == "1"                              # input untouched
    assert num_islands([]) == 0 and num_islands([list("0")]) == 0
    assert num_islands([list("101"), list("010"), list("101")]) == 5   # diagonals do not connect
    rng = random.Random(67)
    for _ in range(500):
        r, c = rng.randint(1, 8), rng.randint(1, 8)
        g = [[rng.choice("01") for _ in range(c)] for _ in range(r)]
        assert num_islands(g) == num_islands_uf(g)
    print("all tests passed")

BFS flood fill on a copy and a union-find version; random grids cross-check the two.

Complexity

Time: O(R * C). Space: O(R * C). Union-find with path compression is effectively linear and handles online additions.

By level

Fresher: Scans the grid and flood-fills each new island with BFS or DFS, explaining why diagonals do not count. States O(R * C).

Mid: Uses an explicit queue to avoid recursion limits, keeps the input unchanged, and offers union-find. Adapts to largest-area and distinct-shape variants.

Senior: Discusses the online version with union-find, very large grids processed in tiles with boundary merging, and memory layout for grid scans. Relates the problem to image segmentation and map region labelling.

Key points

  • Islands are connected components of a grid graph
  • Count one per new flood fill
  • Mark on enqueue
  • 4-directional only unless told otherwise
  • BFS avoids recursion depth issues

Common mistakes

  • Counting diagonal neighbours
  • Recursing on large grids in Python
  • Modifying the input without asking
  • Marking on dequeue, causing duplicate enqueues

Follow-ups

  • How do you return the largest island area?
  • How would you handle cells turning into land one at a time?
  • How would you count distinct island shapes?

Tips

  • Ask whether the grid may be modified
  • Mention the recursion risk
  • Offer union-find for the dynamic version

Evaluation rubric

  • Correct component count
  • Correct neighbour rule
  • O(R * C)
  • Discusses mutation and recursion
68.algorithms-0068Mediummid

Topological sort: order the tasks of a dependency graph so every prerequisite comes first, and report when a cycle makes that impossible.

Kahn's algorithm counts in-degrees, starts a queue with every node of in-degree 0, and repeatedly removes a node and decrements its neighbours, enqueuing any that reach 0. If fewer than V nodes come out, there is a cycle. The DFS method outputs nodes in reverse post-order and detects cycles with a grey (in-progress) colour. Both are O(V + E).

Full answer

Problem

Given n tasks 0..n-1 and edges (u, v) meaning u must be done before v, return an order containing every task that respects all edges, or [] if no such order exists.

Example: edges [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)] with n = 6 has valid orders such as [4, 5, 2, 0, 3, 1]. Edges [(0, 1), (1, 2), (2, 0)] form a cycle, so the answer is [].

Constraints: up to 10^5 nodes and edges.

Brute force

Try all n! permutations and check each against every edge: O(n! * E). Only usable for tiny graphs (the tests use it up to 6 nodes as a reference).

Optimal approach

Kahn's algorithm (BFS):

  1. Build adjacency lists and in-degree counts.
  2. Queue every node with in-degree 0.
  3. Pop u, append to the order, and decrement the in-degree of each neighbour; enqueue those reaching 0.
  4. If the order has n nodes, return it; otherwise there is a cycle.

DFS alternative: colour nodes white, grey (on the current path), black (done). Append a node when it turns black; reverse at the end. Meeting a grey node means a back edge, which means a cycle.

Why it works

A node with in-degree 0 has no unfinished prerequisites, so it is safe to place next; removing it cannot create new constraints. In a DAG some node always has in-degree 0, so Kahn's algorithm only stops early when every remaining node lies on or behind a cycle. In the DFS version, a node finishes only after everything reachable from it has finished, so reverse finishing order puts each node before its descendants.

Complexity

O(V + E) time and space for both methods.

Code

python
import random
from collections import deque
from itertools import permutations


def topo_kahn(n, edges):
    """Kahn's algorithm. Returns an order, or [] if the graph has a cycle. O(V + E)."""
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:                   # u must come before v
        adj[u].append(v)
        indeg[v] += 1
    q = deque(u for u in range(n) if indeg[u] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []


def topo_dfs(n, edges):
    """DFS with three colours; reverse post-order is a topological order."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color, out = [WHITE] * n, []
    for s in range(n):
        if color[s] != WHITE:
            continue
        stack = [(s, iter(adj[s]))]
        color[s] = GREY
        while stack:
            u, it = stack[-1]
            nxt = next(it, None)
            if nxt is None:
                color[u] = BLACK
                out.append(u)
                stack.pop()
            elif color[nxt] == GREY:
                return []                # back edge: cycle
            elif color[nxt] == WHITE:
                color[nxt] = GREY
                stack.append((nxt, iter(adj[nxt])))
    return out[::-1]


def is_valid_order(n, edges, order):
    pos = {u: i for i, u in enumerate(order)}
    return len(order) == n and all(pos[u] < pos[v] for u, v in edges)


def brute_has_order(n, edges):
    return any(is_valid_order(n, edges, p) for p in permutations(range(n)))


if __name__ == "__main__":
    edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
    for f in (topo_kahn, topo_dfs):
        assert is_valid_order(6, edges, f(6, edges))
        assert f(3, [(0, 1), (1, 2), (2, 0)]) == []
        assert f(1, [(0, 0)]) == []                     # self loop is a cycle
        assert f(3, []) != []
    rng = random.Random(68)
    for _ in range(400):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 8))]
        possible = brute_has_order(n, es)
        for f in (topo_kahn, topo_dfs):
            got = f(n, es)
            assert (got != []) == possible
            if got:
                assert is_valid_order(n, es, got)
    print("all tests passed")

Save as b68_topo_sort.py and run python3 b68_topo_sort.py. It prints all tests passed (Python 3.13.5).

Edge cases

No edges (any order). Self-loop (a cycle). Several components. Duplicate edges (in-degree counts each, which is still consistent). Very deep chains: the DFS code here uses an explicit stack of iterators, so no recursion limit.

Pattern

Dependency ordering on a DAG. It solves course schedule, build systems, spreadsheet recalculation, package installation order, and is the first step for DP on DAGs (longest path, counting paths). Using a min-heap instead of a queue in Kahn's algorithm gives the lexicographically smallest order.

python
import random
from collections import deque
from itertools import permutations


def topo_kahn(n, edges):
    """Kahn's algorithm. Returns an order, or [] if the graph has a cycle. O(V + E)."""
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:                   # u must come before v
        adj[u].append(v)
        indeg[v] += 1
    q = deque(u for u in range(n) if indeg[u] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []


def topo_dfs(n, edges):
    """DFS with three colours; reverse post-order is a topological order."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color, out = [WHITE] * n, []
    for s in range(n):
        if color[s] != WHITE:
            continue
        stack = [(s, iter(adj[s]))]
        color[s] = GREY
        while stack:
            u, it = stack[-1]
            nxt = next(it, None)
            if nxt is None:
                color[u] = BLACK
                out.append(u)
                stack.pop()
            elif color[nxt] == GREY:
                return []                # back edge: cycle
            elif color[nxt] == WHITE:
                color[nxt] = GREY
                stack.append((nxt, iter(adj[nxt])))
    return out[::-1]


def is_valid_order(n, edges, order):
    pos = {u: i for i, u in enumerate(order)}
    return len(order) == n and all(pos[u] < pos[v] for u, v in edges)


def brute_has_order(n, edges):
    return any(is_valid_order(n, edges, p) for p in permutations(range(n)))


if __name__ == "__main__":
    edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
    for f in (topo_kahn, topo_dfs):
        assert is_valid_order(6, edges, f(6, edges))
        assert f(3, [(0, 1), (1, 2), (2, 0)]) == []
        assert f(1, [(0, 0)]) == []                     # self loop is a cycle
        assert f(3, []) != []
    rng = random.Random(68)
    for _ in range(400):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 8))]
        possible = brute_has_order(n, es)
        for f in (topo_kahn, topo_dfs):
            got = f(n, es)
            assert (got != []) == possible
            if got:
                assert is_valid_order(n, es, got)
    print("all tests passed")

Kahn's algorithm and an iterative three-colour DFS; random small graphs are checked against exhaustive permutation search.

Complexity

Time: O(V + E). Space: O(V + E). A heap in place of the queue gives the smallest lexicographic order at O((V + E) log V).

By level

Fresher: Explains prerequisites with in-degrees and runs Kahn's algorithm on a small example. Detects a cycle when nodes remain.

Mid: Implements both Kahn and DFS methods with cycle detection and explains why each is correct. Adapts the queue to compute parallel rounds.

Senior: Discusses incremental topological order when edges are added, build systems that recompute only affected nodes, and very large dependency graphs. Explains DP on DAGs built on the topological order.

Key points

  • Start from in-degree 0 nodes
  • Fewer than V output nodes means a cycle
  • DFS: reverse post-order
  • Grey node on the path means a back edge
  • Both O(V + E)

Common mistakes

  • Reversing edge direction by mistake
  • Forgetting the cycle check at the end
  • Treating black (finished) nodes as cycle evidence in DFS
  • Recursion depth on long chains

Follow-ups

  • How do you get the lexicographically smallest order?
  • How would you schedule tasks in parallel rounds and find the minimum number of rounds?
  • How do you find the longest path in a DAG?

Tips

  • Confirm the edge direction
  • Explain why in-degree 0 is safe
  • Mention the cycle signal for both methods

Evaluation rubric

  • Correct order
  • Detects cycles
  • Correct complexity
  • Knows both methods
69.algorithms-0069Mediummid

Dijkstra's algorithm: compute shortest distances from a source in a graph with non-negative edge weights, and state the complexity the heap implementation actually has.

Keep a distance array and a min-heap of (distance, node). Pop the smallest entry, skip it if stale, and relax every outgoing edge, pushing improved distances. With a binary heap and lazy deletion, each edge pushes at most one entry, so the cost is O((V + E) log V) time and O(V + E) space. The heap-free array version is O(V^2 + E). Negative weights break the algorithm.

Full answer

Problem

Given a directed graph with n nodes, weighted edges (u, v, w) with w >= 0, and a source, return the shortest distance to every node (infinity if unreachable).

Example: edges (0,1,4), (0,2,1), (2,1,2), (1,3,1), (2,3,5) from 0 give distances [0, 3, 1, 4]: the best route to 1 is 0 to 2 to 1 with cost 3.

Constraints: up to 10^5 nodes and 2 * 10^5 edges; weights from 0 to 10^4.

Brute force

Bellman-Ford: relax all E edges V - 1 times, O(V * E). Correct for non-negative weights too, but far slower on large sparse graphs. Plain BFS is wrong because it ignores weights.

Optimal approach

  1. dist[src] = 0, all others infinity; heap [(0, src)].
  2. Pop (d, u). If d > dist[u], the entry is stale; skip it.
  3. For each edge (u, v, w): if d + w < dist[v], set dist[v] = d + w and push (dist[v], v).

Python's heapq has no decrease-key, so improved distances are pushed again and old entries are skipped (lazy deletion).

Why it works

When a node is popped with a non-stale distance, no shorter path to it can exist: any other path must leave the set of finalised nodes through some frontier node whose tentative distance is already at least d, and non-negative weights can only add to that. So each node's distance is final the first time it is popped. A negative edge breaks this argument, because a path through a later node could become cheaper.

Complexity

Correction to the earlier version of this item: the code below uses a binary heap with lazy deletion, so the complexity is O((V + E) log V) time, not O(V^2) and not O(E) alone.

  • Each edge relaxation can push one entry, so the heap holds O(E) entries and every push or pop costs O(log E). Since E <= V^2, log E <= 2 log V, which gives O((V + E) log V).
  • Space: O(V + E) for the adjacency list, the distances and the heap entries.
  • The array version (scan for the minimum unvisited node, no heap) is O(V^2 + E), which is better only for dense graphs where E is close to V^2. Fibonacci heaps give O(E + V log V) in theory but are rarely used in practice.

Code

python
import heapq
import random


def dijkstra(n, edges, src):
    """Binary-heap Dijkstra with lazy deletion. Non-negative weights only.
    Each edge can push one heap entry, so the heap holds O(E) items:
    O((V + E) log V) time (log E <= 2 log V), O(V + E) space."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                     # stale entry: u was already finalised with a smaller d
        for v, w in adj[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist


def dijkstra_array(n, edges, src):
    """Array version without a heap: pick the closest unvisited node by scanning. O(V^2 + E).
    Better than the heap only for dense graphs where E is close to V^2."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist, done = [INF] * n, [False] * n
    dist[src] = 0
    for _ in range(n):
        u = min((i for i in range(n) if not done[i]), key=lambda i: dist[i])
        if dist[u] == INF:
            break
        done[u] = True
        for v, w in adj[u]:
            dist[v] = min(dist[v], dist[u] + w)
    return dist


def bellman_ford_ref(n, edges, src):
    INF = float("inf")
    d = [INF] * n
    d[src] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
    return d


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
    assert dijkstra(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra_array(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra(3, [(0, 1, 0)], 0) == [0, 0, float("inf")]   # zero weight, unreachable node
    rng = random.Random(69)
    for _ in range(500):
        n = rng.randint(1, 9)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 9)) for _ in range(rng.randint(0, 25))]
        s = rng.randrange(n)
        assert dijkstra(n, es, s) == dijkstra_array(n, es, s) == bellman_ford_ref(n, es, s)
    print("all tests passed")

Save as b69_dijkstra.py and run python3 b69_dijkstra.py. It prints all tests passed (Python 3.13.5).

Edge cases

Unreachable nodes stay infinity. Zero-weight edges are allowed. Self-loops and parallel edges are harmless. Negative weights: use Bellman-Ford. Early exit: if only one target matters, stop when it is popped.

Pattern

Greedy shortest paths with a priority queue. Variants: path reconstruction with parent pointers, shortest path with a limited number of stops (state expansion), minimum effort or maximum probability paths (change the combine and compare operations), and A* (add an admissible heuristic to the priority).

python
import heapq
import random


def dijkstra(n, edges, src):
    """Binary-heap Dijkstra with lazy deletion. Non-negative weights only.
    Each edge can push one heap entry, so the heap holds O(E) items:
    O((V + E) log V) time (log E <= 2 log V), O(V + E) space."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                     # stale entry: u was already finalised with a smaller d
        for v, w in adj[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist


def dijkstra_array(n, edges, src):
    """Array version without a heap: pick the closest unvisited node by scanning. O(V^2 + E).
    Better than the heap only for dense graphs where E is close to V^2."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist, done = [INF] * n, [False] * n
    dist[src] = 0
    for _ in range(n):
        u = min((i for i in range(n) if not done[i]), key=lambda i: dist[i])
        if dist[u] == INF:
            break
        done[u] = True
        for v, w in adj[u]:
            dist[v] = min(dist[v], dist[u] + w)
    return dist


def bellman_ford_ref(n, edges, src):
    INF = float("inf")
    d = [INF] * n
    d[src] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
    return d


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
    assert dijkstra(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra_array(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra(3, [(0, 1, 0)], 0) == [0, 0, float("inf")]   # zero weight, unreachable node
    rng = random.Random(69)
    for _ in range(500):
        n = rng.randint(1, 9)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 9)) for _ in range(rng.randint(0, 25))]
        s = rng.randrange(n)
        assert dijkstra(n, es, s) == dijkstra_array(n, es, s) == bellman_ford_ref(n, es, s)
    print("all tests passed")

Heap version with lazy deletion and the O(V^2 + E) array version, both cross-checked against Bellman-Ford on random graphs including zero weights.

Complexity

Time: O((V + E) log V) heap version; O(V^2 + E) array version. Space: O(V + E). Fix applied: the claim now matches the code. Lazy deletion allows O(E) heap entries, and log E <= 2 log V.

By level

Fresher: Implements the heap version and traces it on the sample graph. Explains that the algorithm needs non-negative weights.

Mid: States O((V + E) log V) for the heap version and O(V^2 + E) for the array version, and picks between them by density. Explains lazy deletion and the correctness argument.

Senior: Discusses A*, bidirectional Dijkstra and contraction hierarchies used in road routing, and the cost of decrease-key heaps. Handles very large graphs with partitioning and precomputed landmarks.

Key points

  • Only for non-negative weights
  • Skip stale heap entries (d > dist[u])
  • A node's distance is final when first popped
  • Heap version O((V + E) log V); array version O(V^2 + E)
  • Use Bellman-Ford for negative weights

Common mistakes

  • Claiming O(V^2) for the heap code or O(V log V) without the edges
  • Not skipping stale entries, which reprocesses nodes
  • Using Dijkstra with negative edges
  • Marking nodes visited when pushed instead of when popped

Follow-ups

  • How do you reconstruct the shortest path?
  • How would you limit the route to at most k edges?
  • When is A* better, and what makes a heuristic admissible?

Tips

  • State the weight condition first
  • Explain lazy deletion in Python
  • Give the complexity for both implementations and when each wins

Evaluation rubric

  • Correct algorithm with stale-entry check
  • Complexity matches the code
  • Explains why negatives fail
  • Knows alternatives
70.algorithms-0070Mediummid

Union-find (disjoint set union): implement find and union with path compression and union by size, and use it to find the edge that creates a cycle.

Each set is a tree with a root representative. find walks to the root and shortens the path on the way; union attaches the smaller tree under the larger root. With both optimisations each operation is O(alpha(n)) amortised, effectively constant. When union finds both endpoints already share a root, that edge closes a cycle.

Full answer

Problem

Implement a disjoint-set structure over 0..n-1 with find(x), union(a, b) and connected(a, b). Then solve "redundant connection": a tree of n nodes (labelled 1..n) had one extra edge added; return the edge that, when removed, leaves a tree (the last such edge in input order).

Example: edges [[1, 2], [1, 3], [2, 3]] return [2, 3]; [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]] return [1, 4].

Constraints: up to 10^5 nodes and union or find operations.

Brute force

For each new edge, run BFS or DFS to see whether its endpoints are already connected: O(V + E) per edge and O(E * (V + E)) overall. Without the two optimisations, a plain union-find can degrade to O(n) per find on a chain-shaped tree.

Optimal approach

  • parent[i] = i, size[i] = 1 at start.
  • find(x): while x is not its own parent, set parent[x] = parent[parent[x]] (path halving) and move up.
  • union(a, b): find both roots; if equal, return False. Otherwise attach the smaller root under the larger and add sizes.
  • Redundant connection: union each edge in order; the first union that returns False is the answer.

Why it works

Two nodes are connected exactly when they have the same root, because unions only ever merge whole trees. Union by size keeps tree height at O(log n), since a node's depth increases only when its tree at least doubles in size. Path compression flattens the trees further, and the combination gives the inverse Ackermann bound. In the redundant edge problem, an edge whose endpoints are already connected is the one that completes a cycle.

Complexity

O(alpha(n)) amortised per operation (alpha is below 5 for any realistic n), O(n) space. Union by size alone gives O(log n) per operation.

Code

python
import random


class DSU:
    """Disjoint set union with path halving and union by size.
    Each operation is O(alpha(n)) amortised, effectively constant."""

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.sets = n

    def find(self, 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):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                 # already connected: this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra             # attach the smaller tree under the larger
        self.size[ra] += self.size[rb]
        self.sets -= 1
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)


def redundant_connection(edges):
    """First edge that joins two already-connected nodes (nodes are 1..n)."""
    dsu = DSU(len(edges) + 1)
    for u, v in edges:
        if not dsu.union(u, v):
            return [u, v]
    return []


def brute_connected(n, edges, a, b):
    adj = {i: set() for i in range(n)}
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    seen, stack = {a}, [a]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return b in seen


if __name__ == "__main__":
    d = DSU(5)
    assert d.union(0, 1) and d.union(3, 4) and not d.union(1, 0)
    assert d.connected(0, 1) and not d.connected(1, 3) and d.sets == 3
    assert redundant_connection([[1, 2], [1, 3], [2, 3]]) == [2, 3]
    assert redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]) == [1, 4]
    rng = random.Random(70)
    for _ in range(300):
        n = rng.randint(1, 15)
        dsu, es = DSU(n), []
        for _ in range(rng.randint(0, 20)):
            u, v = rng.randrange(n), rng.randrange(n)
            dsu.union(u, v)
            es.append((u, v))
            a, b = rng.randrange(n), rng.randrange(n)
            assert dsu.connected(a, b) == brute_connected(n, es, a, b)
    print("all tests passed")

Save as b70_union_find.py and run python3 b70_union_find.py. It prints all tests passed (Python 3.13.5).

Edge cases

union(x, x) (already connected). Nodes labelled from 1 (allocate n + 1). Counting sets: start at n and decrement on each successful union. Union-find does not support splitting sets; deletions need a different structure or offline processing.

Pattern

Incremental connectivity. Union-find powers Kruskal's MST, number of islands with additions, accounts merge (group emails), equations with equality and inequality constraints, and percolation simulations. Weighted union-find extends it to "a / b = k" style relations.

python
import random


class DSU:
    """Disjoint set union with path halving and union by size.
    Each operation is O(alpha(n)) amortised, effectively constant."""

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.sets = n

    def find(self, 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):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                 # already connected: this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra             # attach the smaller tree under the larger
        self.size[ra] += self.size[rb]
        self.sets -= 1
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)


def redundant_connection(edges):
    """First edge that joins two already-connected nodes (nodes are 1..n)."""
    dsu = DSU(len(edges) + 1)
    for u, v in edges:
        if not dsu.union(u, v):
            return [u, v]
    return []


def brute_connected(n, edges, a, b):
    adj = {i: set() for i in range(n)}
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    seen, stack = {a}, [a]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return b in seen


if __name__ == "__main__":
    d = DSU(5)
    assert d.union(0, 1) and d.union(3, 4) and not d.union(1, 0)
    assert d.connected(0, 1) and not d.connected(1, 3) and d.sets == 3
    assert redundant_connection([[1, 2], [1, 3], [2, 3]]) == [2, 3]
    assert redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]) == [1, 4]
    rng = random.Random(70)
    for _ in range(300):
        n = rng.randint(1, 15)
        dsu, es = DSU(n), []
        for _ in range(rng.randint(0, 20)):
            u, v = rng.randrange(n), rng.randrange(n)
            dsu.union(u, v)
            es.append((u, v))
            a, b = rng.randrange(n), rng.randrange(n)
            assert dsu.connected(a, b) == brute_connected(n, es, a, b)
    print("all tests passed")

DSU with path halving and union by size, the redundant-connection solver, and random checks of connected() against BFS reachability.

Complexity

Time: O(alpha(n)) amortised per operation. Space: O(n). Union by size alone gives O(log n); path compression alone gives O(log n) amortised; together they give alpha(n).

By level

Fresher: Implements find and union and explains that same root means same group. Uses it to detect the extra edge in a small example.

Mid: Adds path compression and union by size and explains the height argument. Applies union-find to islands with additions and to Kruskal.

Senior: Discusses rollback DSU for offline queries, weighted union-find for relative values, and concurrency issues when sharing a DSU across threads. Compares union-find with graph traversal for dynamic connectivity workloads.

Key points

  • Same root means same set
  • Union by size bounds height
  • Path compression flattens trees
  • Combined cost is inverse Ackermann
  • Failed union means a cycle edge

Common mistakes

  • Comparing parents instead of roots
  • Attaching the larger tree under the smaller
  • Forgetting to update size on the new root only
  • Expecting union-find to support deletions

Follow-ups

  • How would you support "undo" of the last union (rollback DSU)?
  • How do you handle relations like a / b = 2 with weighted union-find?
  • How would you process edge deletions offline?

Tips

  • Explain why both optimisations matter
  • State alpha(n) as effectively constant
  • Show the redundant-edge use

Evaluation rubric

  • Correct find and union
  • Both optimisations
  • Correct application
  • Correct complexity
71.algorithms-0071Mediummid

Cycle detection: decide whether a graph contains a cycle, once for an undirected graph and once for a directed graph, and explain why the two need different checks.

In an undirected graph, a DFS that reaches an already visited node through an edge other than the one it arrived on has found a cycle; union-find gives the same answer by checking whether an edge joins nodes already connected. In a directed graph, reaching a visited node is not enough: only an edge back to a node still on the current DFS path (grey) forms a cycle. All methods are O(V + E).

Full answer

Problem

Given n nodes and an edge list, return whether the graph contains a cycle. Solve it for an undirected graph and for a directed graph.

Example: undirected [(0,1), (1,2), (2,0)] has a cycle; directed [(0,1), (0,2), (1,2)] (a diamond) has none, even though node 2 is reached twice. A directed self-loop (0,0) is a cycle.

Constraints: up to 10^5 nodes and edges; parallel edges and self-loops may appear.

Brute force

Directed: try every ordering of nodes; the graph is acyclic exactly when some ordering puts every edge forward (O(n! * E)). Undirected: for each edge, remove it and test whether its endpoints are still connected (O(E * (V + E))).

Optimal approach

Undirected DFS: track the edge id used to reach each node; when scanning neighbours, skip the arriving edge and report a cycle if any other edge leads to a visited node. Tracking edge ids (not the parent node) makes a doubled edge u-v count as a cycle.

Directed DFS with three colours: white (unvisited), grey (on the current path), black (fully explored). An edge to a grey node is a back edge, which means a cycle. Edges to black nodes are fine.

Union-find (undirected only): an edge whose endpoints already share a root closes a cycle.

Why it works

Undirected: a DFS tree plus one more edge between already visited nodes always forms a cycle, because the two endpoints are already connected through the tree. Directed: a cycle exists exactly when DFS finds a back edge to an ancestor on the current path. An edge into a black node points to a finished subtree that cannot reach back to the current path, otherwise that node would not be finished. That is why the undirected check gives false positives on directed diamonds.

Complexity

O(V + E) time, O(V) space for all three methods (union-find is O(E * alpha(V))).

Code

python
import random
from itertools import permutations


def has_cycle_undirected(n, edges):
    """Iterative DFS that remembers each node's parent edge. O(V + E).
    Edge ids (not parent nodes) are tracked, so a duplicated edge u-v counts as a cycle."""
    adj = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        adj[u].append((v, i))
        adj[v].append((u, i))
    seen = [False] * n
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        stack = [(s, -1)]
        while stack:
            u, via = stack.pop()
            for v, eid in adj[u]:
                if eid == via:
                    continue             # do not walk straight back along the same edge
                if seen[v]:
                    return True
                seen[v] = True
                stack.append((v, eid))
    return False


def has_cycle_directed(n, edges):
    """Three colours: reaching a GREY node (on the current DFS path) means a back edge."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color = [WHITE] * n
    for s in range(n):
        if color[s] != WHITE:
            continue
        color[s] = GREY
        stack = [(s, iter(adj[s]))]
        while stack:
            u, it = stack[-1]
            v = next(it, None)
            if v is None:
                color[u] = BLACK
                stack.pop()
            elif color[v] == GREY:
                return True
            elif color[v] == WHITE:
                color[v] = GREY
                stack.append((v, iter(adj[v])))
    return False


def brute_undirected(n, edges):
    """A forest has exactly n - components edges; any extra edge makes a cycle."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            x = parent[x]
        return x
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            return True
        parent[ru] = rv
    return False


def brute_directed(n, edges):
    """Acyclic exactly when some ordering puts every edge forward."""
    return not any(all(p.index(u) < p.index(v) for u, v in edges) for p in permutations(range(n)))


if __name__ == "__main__":
    assert not has_cycle_undirected(4, [(0, 1), (1, 2), (2, 3)])
    assert has_cycle_undirected(3, [(0, 1), (1, 2), (2, 0)])
    assert has_cycle_undirected(2, [(0, 1), (0, 1)])          # parallel edges
    assert has_cycle_directed(3, [(0, 1), (1, 2), (2, 0)])
    assert not has_cycle_directed(3, [(0, 1), (0, 2), (1, 2)])  # diamond, not a cycle
    assert has_cycle_directed(1, [(0, 0)])
    rng = random.Random(71)
    for _ in range(500):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 7))]
        assert has_cycle_directed(n, es) == brute_directed(n, es)
        assert has_cycle_undirected(n, es) == brute_undirected(n, es)
    print("all tests passed")

Save as b71_cycle_detection.py and run python3 b71_cycle_detection.py. It prints all tests passed (Python 3.13.5).

Edge cases

Self-loops (cycle in both versions). Parallel undirected edges (cycle of length 2). Disconnected graphs (start a DFS from every unvisited node). Directed diamonds (no cycle). Deep graphs: the code uses explicit stacks.

Pattern

Back-edge detection in DFS. Directed cycle checks drive course schedule feasibility, deadlock detection in wait-for graphs, and dependency validation. Undirected cycle checks drive MST construction and "graph valid tree" (connected and E = V - 1).

python
import random
from itertools import permutations


def has_cycle_undirected(n, edges):
    """Iterative DFS that remembers each node's parent edge. O(V + E).
    Edge ids (not parent nodes) are tracked, so a duplicated edge u-v counts as a cycle."""
    adj = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        adj[u].append((v, i))
        adj[v].append((u, i))
    seen = [False] * n
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        stack = [(s, -1)]
        while stack:
            u, via = stack.pop()
            for v, eid in adj[u]:
                if eid == via:
                    continue             # do not walk straight back along the same edge
                if seen[v]:
                    return True
                seen[v] = True
                stack.append((v, eid))
    return False


def has_cycle_directed(n, edges):
    """Three colours: reaching a GREY node (on the current DFS path) means a back edge."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color = [WHITE] * n
    for s in range(n):
        if color[s] != WHITE:
            continue
        color[s] = GREY
        stack = [(s, iter(adj[s]))]
        while stack:
            u, it = stack[-1]
            v = next(it, None)
            if v is None:
                color[u] = BLACK
                stack.pop()
            elif color[v] == GREY:
                return True
            elif color[v] == WHITE:
                color[v] = GREY
                stack.append((v, iter(adj[v])))
    return False


def brute_undirected(n, edges):
    """A forest has exactly n - components edges; any extra edge makes a cycle."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            x = parent[x]
        return x
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            return True
        parent[ru] = rv
    return False


def brute_directed(n, edges):
    """Acyclic exactly when some ordering puts every edge forward."""
    return not any(all(p.index(u) < p.index(v) for u, v in edges) for p in permutations(range(n)))


if __name__ == "__main__":
    assert not has_cycle_undirected(4, [(0, 1), (1, 2), (2, 3)])
    assert has_cycle_undirected(3, [(0, 1), (1, 2), (2, 0)])
    assert has_cycle_undirected(2, [(0, 1), (0, 1)])          # parallel edges
    assert has_cycle_directed(3, [(0, 1), (1, 2), (2, 0)])
    assert not has_cycle_directed(3, [(0, 1), (0, 2), (1, 2)])  # diamond, not a cycle
    assert has_cycle_directed(1, [(0, 0)])
    rng = random.Random(71)
    for _ in range(500):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 7))]
        assert has_cycle_directed(n, es) == brute_directed(n, es)
        assert has_cycle_undirected(n, es) == brute_undirected(n, es)
    print("all tests passed")

Undirected DFS that skips only the arriving edge id, directed three-colour DFS, and brute force references (union-find and permutation search).

Complexity

Time: O(V + E). Space: O(V). Both DFS versions use explicit stacks, so recursion depth is not an issue.

By level

Fresher: Detects cycles in undirected graphs with DFS and a parent check, and explains why directed graphs need more care. Uses the diamond as an example.

Mid: Implements three-colour DFS for directed graphs and union-find for undirected ones. Handles parallel edges and returns the cycle when asked.

Senior: Discusses deadlock detection in wait-for graphs, incremental cycle checks as edges arrive, and cycle detection in very large dependency graphs. Connects back edges to strongly connected components.

Key points

  • Undirected: visited neighbour via a different edge means a cycle
  • Directed: edge to a grey node means a cycle
  • Black nodes are safe
  • Union-find works for undirected only
  • Start from every unvisited node

Common mistakes

  • Using the undirected rule on directed graphs
  • Skipping the parent node instead of the parent edge and missing parallel edges
  • Treating any visited node as a cycle in directed graphs
  • Only checking from node 0

Follow-ups

  • How would you return the actual cycle?
  • How do you check whether an undirected graph is a valid tree?
  • How would you detect deadlocks in a distributed system?

Tips

  • Explain why directed needs three colours
  • Draw the diamond counterexample
  • Mention union-find for undirected graphs

Evaluation rubric

  • Correct undirected and directed checks
  • Explains the difference
  • Handles self-loops and parallel edges
  • Correct complexity
72.algorithms-0072Mediumfresher

Check whether a graph is bipartite: decide if its nodes can be split into two groups so that every edge connects nodes from different groups.

Try to colour the graph with two colours using BFS: give the start colour 0, every neighbour the opposite colour, and fail if an edge joins two nodes of the same colour. Repeat from each uncoloured node to cover all components. A graph is bipartite exactly when it has no odd-length cycle. Time O(V + E).

Full answer

Problem

Given an undirected graph as adjacency lists for nodes 0..n-1, return True if it is bipartite.

Example: a 4-cycle 0-1-2-3-0 is bipartite (groups {0, 2} and {1, 3}); a triangle is not.

Constraints: up to 100 nodes in the classic version, up to 10^5 in larger variants; the graph may be disconnected; a self-loop makes it non-bipartite.

Brute force

Try all 2^n assignments of nodes to two groups and check every edge: O(2^n * E).

Optimal approach

BFS two-colouring:

  1. color = [-1] * n.
  2. For each uncoloured node s: colour it 0 and BFS.
  3. For each neighbour v of u: if uncoloured, give it 1 - color[u] and enqueue; if it has the same colour as u, return False.
  4. If every component finishes, return True.

Why it works

Within one component, once the start colour is fixed, every other node's colour is forced: it must differ from its BFS parent. So if any valid split exists, BFS finds it, and a conflict means no split exists. A conflict always comes from an odd cycle, because walking around a cycle flips colour at each edge, which returns to the start colour only after an even number of steps.

Complexity

O(V + E) time, O(V) space.

Code

python
import random
from collections import deque
from itertools import product


def is_bipartite(adj):
    """2-colour each component with BFS. Fails when an edge joins two nodes of the same colour.
    O(V + E). adj is a list of neighbour lists (undirected)."""
    n = len(adj)
    color = [-1] * n
    for s in range(n):
        if color[s] != -1:
            continue
        color[s] = 0
        q = deque([s])
        while q:
            u = q.popleft()
            for v in adj[u]:
                if color[v] == -1:
                    color[v] = 1 - color[u]
                    q.append(v)
                elif color[v] == color[u]:
                    return False         # odd cycle
    return True


def brute(adj):
    n = len(adj)
    return any(all(c[u] != c[v] for u in range(n) for v in adj[u]) for c in product((0, 1), repeat=n))


if __name__ == "__main__":
    square = [[1, 3], [0, 2], [1, 3], [0, 2]]
    triangle = [[1, 2], [0, 2], [0, 1]]
    assert is_bipartite(square) and not is_bipartite(triangle)
    assert is_bipartite([]) and is_bipartite([[]])
    assert not is_bipartite([[0]])                       # self loop
    two_parts = [[1], [0], [3, 4], [2, 4], [2, 3]]       # second component is a triangle
    assert not is_bipartite(two_parts)
    rng = random.Random(72)
    for _ in range(500):
        n = rng.randint(1, 8)
        adj = [[] for _ in range(n)]
        for _ in range(rng.randint(0, 10)):
            u, v = rng.randrange(n), rng.randrange(n)
            adj[u].append(v)
            adj[v].append(u)
        assert is_bipartite(adj) == brute(adj)
    print("all tests passed")

Save as b72_bipartite.py and run python3 b72_bipartite.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty graph and a single node (bipartite). Self-loop (not bipartite). Several components, one of them odd. Isolated nodes.

Pattern

Two-colouring by forced choices. Uses: splitting people into two teams given "dislikes" pairs, scheduling with two time slots, detecting odd cycles, and the first step of bipartite matching (job assignment, Hopcroft-Karp). Union-find also works: union each node's neighbours together and fail if a node ends up with its own neighbour.

python
import random
from collections import deque
from itertools import product


def is_bipartite(adj):
    """2-colour each component with BFS. Fails when an edge joins two nodes of the same colour.
    O(V + E). adj is a list of neighbour lists (undirected)."""
    n = len(adj)
    color = [-1] * n
    for s in range(n):
        if color[s] != -1:
            continue
        color[s] = 0
        q = deque([s])
        while q:
            u = q.popleft()
            for v in adj[u]:
                if color[v] == -1:
                    color[v] = 1 - color[u]
                    q.append(v)
                elif color[v] == color[u]:
                    return False         # odd cycle
    return True


def brute(adj):
    n = len(adj)
    return any(all(c[u] != c[v] for u in range(n) for v in adj[u]) for c in product((0, 1), repeat=n))


if __name__ == "__main__":
    square = [[1, 3], [0, 2], [1, 3], [0, 2]]
    triangle = [[1, 2], [0, 2], [0, 1]]
    assert is_bipartite(square) and not is_bipartite(triangle)
    assert is_bipartite([]) and is_bipartite([[]])
    assert not is_bipartite([[0]])                       # self loop
    two_parts = [[1], [0], [3, 4], [2, 4], [2, 3]]       # second component is a triangle
    assert not is_bipartite(two_parts)
    rng = random.Random(72)
    for _ in range(500):
        n = rng.randint(1, 8)
        adj = [[] for _ in range(n)]
        for _ in range(rng.randint(0, 10)):
            u, v = rng.randrange(n), rng.randrange(n)
            adj[u].append(v)
            adj[v].append(u)
        assert is_bipartite(adj) == brute(adj)
    print("all tests passed")

BFS two-colouring over all components, checked against all 2^n colourings on random small graphs.

Complexity

Time: O(V + E). Space: O(V). DFS colouring gives the same bound.

By level

Fresher: Colours nodes alternately with BFS and fails on a same-colour edge, using the triangle as an example. Loops over all components.

Mid: Explains why a conflict means an odd cycle and returns the two groups. Solves the dislikes-pairs variant with the same code.

Senior: Connects bipartite checks to matching and assignment problems and discusses scale for large graphs. Mentions the union-find formulation and when it is preferable for streaming edges.

Key points

  • Colour neighbours with the opposite colour
  • Same-colour edge means not bipartite
  • Not bipartite exactly when an odd cycle exists
  • Loop over all components
  • O(V + E)

Common mistakes

  • Only checking the component of node 0
  • Forgetting self-loops
  • Using 2 colours but not detecting conflicts on already coloured nodes
  • Treating directed edges as one-way

Follow-ups

  • How would you return the two groups?
  • How does bipartite matching build on this?
  • How do you split people who dislike each other into two groups?

Tips

  • Mention the odd-cycle characterization
  • Handle disconnected graphs
  • Show a triangle as the smallest failure

Evaluation rubric

  • Correct colouring
  • Covers all components
  • Explains odd cycles
  • Correct complexity
73.algorithms-0073Hardsenior

Minimum spanning tree: connect all nodes of a weighted undirected graph at the lowest total edge cost, using both Kruskal's and Prim's algorithms.

Kruskal sorts edges by weight and adds each edge that joins two different components, using union-find: O(E log E). Prim grows one tree from a start node, always taking the cheapest edge leaving the tree from a min-heap: O(E log V). Both are correct by the cut property. If the graph is disconnected there is no spanning tree.

Full answer

Problem

Given n nodes and undirected weighted edges (u, v, w), return the minimum total weight of a spanning tree (a set of n - 1 edges connecting all nodes without cycles), or None if the graph is disconnected.

Example: n = 6 with edges (0,1,4), (0,2,3), (1,2,1), (1,3,2), (2,3,4), (3,4,2), (4,5,6) has MST weight 14 using edges of weight 1, 2, 2, 3 and 6.

Constraints: up to 10^4 nodes and 10^5 edges; weights are positive integers.

Brute force

Enumerate every subset of n - 1 edges, keep those that form a tree, and take the cheapest: O(C(E, n-1) * n), exponential.

Optimal approach

Kruskal: sort edges by weight; for each edge, if its endpoints are in different union-find sets, add it and union them; stop after n - 1 edges.

Prim: start at node 0 with a heap of (weight, node). Pop the cheapest entry; if the node is new, add the weight and push all its edges to nodes outside the tree. Stop when all n nodes are in.

Why it works

Cut property: for any split of the nodes into two groups, the cheapest edge crossing the split belongs to some MST. Kruskal's next edge is the cheapest edge between its two components, and Prim's next edge is the cheapest edge leaving the current tree; in both cases that edge is the cheapest across some cut, so adding it keeps the partial solution extendable to an optimal tree. Skipping an edge inside one component avoids cycles.

Complexity

Kruskal: O(E log E) for sorting plus near-constant union-find, O(V + E) space. Prim with a binary heap and lazy deletion: O(E log V) time (log E and log V differ by at most a factor of 2), O(V + E) space. Prim with an array is O(V^2), good for dense graphs.

Code

python
import heapq
import random
from itertools import combinations


def kruskal(n, edges):
    """Sort edges by weight, add each one that joins two different components.
    O(E log E) for the sort plus near-constant union-find. Returns (total, edges) or None."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total, chosen = 0, []
    for w, u, v in sorted((w, u, v) for u, v, w in edges):
        ru, rv = find(u), find(v)
        if ru != rv:
            parent[ru] = rv
            total += w
            chosen.append((u, v, w))
            if len(chosen) == n - 1:
                break
    return (total, chosen) if len(chosen) == n - 1 else None


def prim(n, edges):
    """Grow one tree from node 0 using a heap of crossing edges. O(E log V)."""
    if n == 0:
        return 0
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    in_tree, total, heap = [False] * n, 0, [(0, 0)]
    added = 0
    while heap and added < n:
        w, u = heapq.heappop(heap)
        if in_tree[u]:
            continue
        in_tree[u] = True
        total += w
        added += 1
        for e in adj[u]:
            if not in_tree[e[1]]:
                heapq.heappush(heap, e)
    return total if added == n else None


def brute(n, edges):
    """Try every subset of n-1 edges that forms a spanning tree."""
    best = None
    for combo in combinations(edges, n - 1):
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                x = parent[x]
            return x
        ok = True
        for u, v, _ in combo:
            ru, rv = find(u), find(v)
            if ru == rv:
                ok = False
                break
            parent[ru] = rv
        if ok:
            s = sum(w for _, _, w in combo)
            best = s if best is None else min(best, s)
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4), (3, 4, 2), (4, 5, 6)]
    total, chosen = kruskal(6, edges)
    assert total == prim(6, edges) == 14 and len(chosen) == 5
    assert kruskal(3, [(0, 1, 1)]) is None and prim(3, [(0, 1, 1)]) is None   # disconnected
    assert kruskal(1, []) == (0, []) and prim(1, []) == 0
    rng = random.Random(73)
    for _ in range(300):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(1, 9)) for _ in range(rng.randint(0, 9))]
        k = kruskal(n, es)
        b = brute(n, es) if n > 1 else 0
        assert (k[0] if k else None) == prim(n, es) == b
    print("all tests passed")

Save as b73_mst.py and run python3 b73_mst.py. It prints all tests passed (Python 3.13.5).

Edge cases

Disconnected graph (return None; or compute a minimum spanning forest if asked). A single node (cost 0). Parallel edges and self-loops (self-loops are never chosen). Equal weights (many MSTs may exist with the same total).

Pattern

Greedy with an exchange argument (the cut property). Applications: network cabling, clustering (remove the k - 1 heaviest MST edges to get k clusters), approximation for metric TSP, and "minimum cost to connect all points" with Manhattan distances (Prim's O(V^2) on the complete graph).

python
import heapq
import random
from itertools import combinations


def kruskal(n, edges):
    """Sort edges by weight, add each one that joins two different components.
    O(E log E) for the sort plus near-constant union-find. Returns (total, edges) or None."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total, chosen = 0, []
    for w, u, v in sorted((w, u, v) for u, v, w in edges):
        ru, rv = find(u), find(v)
        if ru != rv:
            parent[ru] = rv
            total += w
            chosen.append((u, v, w))
            if len(chosen) == n - 1:
                break
    return (total, chosen) if len(chosen) == n - 1 else None


def prim(n, edges):
    """Grow one tree from node 0 using a heap of crossing edges. O(E log V)."""
    if n == 0:
        return 0
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    in_tree, total, heap = [False] * n, 0, [(0, 0)]
    added = 0
    while heap and added < n:
        w, u = heapq.heappop(heap)
        if in_tree[u]:
            continue
        in_tree[u] = True
        total += w
        added += 1
        for e in adj[u]:
            if not in_tree[e[1]]:
                heapq.heappush(heap, e)
    return total if added == n else None


def brute(n, edges):
    """Try every subset of n-1 edges that forms a spanning tree."""
    best = None
    for combo in combinations(edges, n - 1):
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                x = parent[x]
            return x
        ok = True
        for u, v, _ in combo:
            ru, rv = find(u), find(v)
            if ru == rv:
                ok = False
                break
            parent[ru] = rv
        if ok:
            s = sum(w for _, _, w in combo)
            best = s if best is None else min(best, s)
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4), (3, 4, 2), (4, 5, 6)]
    total, chosen = kruskal(6, edges)
    assert total == prim(6, edges) == 14 and len(chosen) == 5
    assert kruskal(3, [(0, 1, 1)]) is None and prim(3, [(0, 1, 1)]) is None   # disconnected
    assert kruskal(1, []) == (0, []) and prim(1, []) == 0
    rng = random.Random(73)
    for _ in range(300):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(1, 9)) for _ in range(rng.randint(0, 9))]
        k = kruskal(n, es)
        b = brute(n, es) if n > 1 else 0
        assert (k[0] if k else None) == prim(n, es) == b
    print("all tests passed")

Kruskal with union-find and Prim with a heap; random small graphs are checked against exhaustive search over edge subsets.

Complexity

Time: O(E log E) Kruskal, O(E log V) Prim. Space: O(V + E). Prim with an adjacency matrix and no heap is O(V^2), better for dense graphs.

By level

Fresher: Explains Kruskal with sorting and union-find on a small graph. Knows that a spanning tree has n - 1 edges.

Mid: Implements both algorithms, explains the cut property, and chooses by density. Handles disconnected graphs.

Senior: Discusses MST-based clustering, Boruvka's algorithm for parallel settings, and updates when edges change. Applies Prim's O(V^2) method to implicit complete graphs such as point sets.

Key points

  • Spanning tree has n - 1 edges
  • Cut property justifies both greedy choices
  • Kruskal = sorted edges + union-find
  • Prim = grow one tree with a min-heap
  • Disconnected graphs have no spanning tree

Common mistakes

  • Adding an edge inside one component and creating a cycle
  • Forgetting to check for disconnection
  • Using Dijkstra's distance-from-source instead of the edge weight in Prim
  • Claiming the MST is unique when weights tie

Follow-ups

  • How would you find the second-best MST?
  • How do you cluster points into k groups with an MST?
  • Which algorithm do you pick for a dense graph?

Tips

  • State the cut property
  • Compare the two algorithms by graph density
  • Handle the disconnected case

Evaluation rubric

  • Correct algorithm(s)
  • Correctness argument
  • Correct complexity
  • Handles disconnection
74.algorithms-0074Hardsenior

0-1 BFS: find shortest paths when every edge weight is 0 or 1 using a deque instead of a priority queue, and apply it to a grid where changing a cell's arrow costs 1.

With weights limited to 0 and 1, a deque can replace Dijkstra's heap: relaxing a 0-edge pushes the node to the front, relaxing a 1-edge pushes it to the back. The deque stays sorted by distance with at most two distinct values, so the run is O(V + E). On a grid of arrows, following the arrow is a 0-edge and any other move is a 1-edge.

Full answer

Problem

Part 1: given a directed graph whose edge weights are 0 or 1, return the shortest distance from a source to every node.

Part 2: each cell of an R x C grid holds an arrow (1 right, 2 left, 3 down, 4 up). Moving along a cell's arrow is free; changing the arrow costs 1. Return the minimum cost to reach the bottom-right cell from the top-left.

Example: for the grid [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] the answer is 3. For [[1,1,3],[3,2,2],[1,1,4]] the answer is 0, because the arrows already lead to the end.

Constraints: up to 10^5 nodes or 100 x 100 cells.

Brute force

Run Dijkstra with a heap: correct, O((V + E) log V). Plain BFS is wrong because it counts every edge as 1.

Optimal approach

Initialise dist[src] = 0, deque [src]. Pop from the front. For each edge (u, v, w), if dist[u] + w < dist[v], update it and push v to the front when w == 0, to the back when w == 1.

For the grid, nodes are cells; from each cell, all 4 moves are edges, with weight 0 if the move matches the arrow and 1 otherwise.

Why it works

The deque always holds nodes whose distance is d at the front and d + 1 at the back, in that order. A 0-edge produces another distance d node, which belongs at the front; a 1-edge produces d + 1, which belongs at the back. So nodes come off the front in non-decreasing distance order, the same order Dijkstra would use, without paying for a heap. A node may be pushed more than once, but only when its distance strictly improves, and the cross-check against heap Dijkstra confirms the distances.

Complexity

O(V + E) time and O(V) space. On the grid: O(R * C) because each cell has 4 edges.

Code

python
import heapq
import random
from collections import deque


def zero_one_bfs(n, edges, src):
    """Shortest paths when every weight is 0 or 1. Deque instead of heap: O(V + E).
    0-weight edges go to the front (same distance), 1-weight edges to the back."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    dq = deque([src])
    while dq:
        u = dq.popleft()
        for v, w in adj[u]:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                if w == 0:
                    dq.appendleft(v)
                else:
                    dq.append(v)
    return dist


def min_flips_grid(grid):
    """Each cell has an arrow 1=right 2=left 3=down 4=up. Following an arrow is free,
    changing it costs 1. Minimum cost from top-left to bottom-right."""
    rows, cols = len(grid), len(grid[0])
    moves = {1: (0, 1), 2: (0, -1), 3: (1, 0), 4: (-1, 0)}
    INF = float("inf")
    dist = [[INF] * cols for _ in range(rows)]
    dist[0][0] = 0
    dq = deque([(0, 0)])
    while dq:
        r, c = dq.popleft()
        for arrow, (dr, dc) in moves.items():
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols:
                w = 0 if grid[r][c] == arrow else 1
                if dist[r][c] + w < dist[nr][nc]:
                    dist[nr][nc] = dist[r][c] + w
                    (dq.appendleft if w == 0 else dq.append)((nr, nc))
    return dist[-1][-1]


def dijkstra_ref(n, edges, src):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    dist = [float("inf")] * n
    dist[src] = 0
    h = [(0, src)]
    while h:
        d, u = heapq.heappop(h)
        if d > dist[u]:
            continue
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(h, (d + w, v))
    return dist


if __name__ == "__main__":
    edges = [(0, 1, 0), (1, 2, 1), (0, 2, 1), (2, 3, 0), (0, 3, 1), (3, 4, 1)]
    assert zero_one_bfs(5, edges, 0) == [0, 0, 1, 1, 2]
    assert min_flips_grid([[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2]]) == 3
    assert min_flips_grid([[1, 1, 3], [3, 2, 2], [1, 1, 4]]) == 0
    assert min_flips_grid([[4]]) == 0
    rng = random.Random(74)
    for _ in range(500):
        n = rng.randint(1, 10)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 1)) for _ in range(rng.randint(0, 25))]
        s = rng.randrange(n)
        assert zero_one_bfs(n, es, s) == dijkstra_ref(n, es, s)
    print("all tests passed")

Save as b74_zero_one_bfs.py and run python3 b74_zero_one_bfs.py. It prints all tests passed (Python 3.13.5).

Edge cases

Single-cell grid (cost 0). Unreachable nodes stay infinity. All weights 0 (everything reachable costs 0). Weights other than 0 and 1 (use Dijkstra, or Dial's buckets for small integer weights).

Pattern

Deque-based shortest paths for binary weights. Variants: minimum walls to remove to reach a target, minimum obstacles in a grid, minimum edge reversals to make a path (original direction 0, reversed 1), and Dial's algorithm for small integer weights.

python
import heapq
import random
from collections import deque


def zero_one_bfs(n, edges, src):
    """Shortest paths when every weight is 0 or 1. Deque instead of heap: O(V + E).
    0-weight edges go to the front (same distance), 1-weight edges to the back."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    dq = deque([src])
    while dq:
        u = dq.popleft()
        for v, w in adj[u]:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                if w == 0:
                    dq.appendleft(v)
                else:
                    dq.append(v)
    return dist


def min_flips_grid(grid):
    """Each cell has an arrow 1=right 2=left 3=down 4=up. Following an arrow is free,
    changing it costs 1. Minimum cost from top-left to bottom-right."""
    rows, cols = len(grid), len(grid[0])
    moves = {1: (0, 1), 2: (0, -1), 3: (1, 0), 4: (-1, 0)}
    INF = float("inf")
    dist = [[INF] * cols for _ in range(rows)]
    dist[0][0] = 0
    dq = deque([(0, 0)])
    while dq:
        r, c = dq.popleft()
        for arrow, (dr, dc) in moves.items():
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols:
                w = 0 if grid[r][c] == arrow else 1
                if dist[r][c] + w < dist[nr][nc]:
                    dist[nr][nc] = dist[r][c] + w
                    (dq.appendleft if w == 0 else dq.append)((nr, nc))
    return dist[-1][-1]


def dijkstra_ref(n, edges, src):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    dist = [float("inf")] * n
    dist[src] = 0
    h = [(0, src)]
    while h:
        d, u = heapq.heappop(h)
        if d > dist[u]:
            continue
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(h, (d + w, v))
    return dist


if __name__ == "__main__":
    edges = [(0, 1, 0), (1, 2, 1), (0, 2, 1), (2, 3, 0), (0, 3, 1), (3, 4, 1)]
    assert zero_one_bfs(5, edges, 0) == [0, 0, 1, 1, 2]
    assert min_flips_grid([[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2]]) == 3
    assert min_flips_grid([[1, 1, 3], [3, 2, 2], [1, 1, 4]]) == 0
    assert min_flips_grid([[4]]) == 0
    rng = random.Random(74)
    for _ in range(500):
        n = rng.randint(1, 10)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 1)) for _ in range(rng.randint(0, 25))]
        s = rng.randrange(n)
        assert zero_one_bfs(n, es, s) == dijkstra_ref(n, es, s)
    print("all tests passed")

Generic 0-1 BFS and the arrow-grid problem, cross-checked against heap Dijkstra on random 0/1-weighted graphs.

Complexity

Time: O(V + E). Space: O(V). Compared with Dijkstra, the log factor disappears because the deque replaces the heap.

By level

Fresher: Explains why plain BFS fails with 0-weight edges, then shows the deque rule on a small example. Models the arrow grid as a graph.

Mid: Implements 0-1 BFS, states the two-value invariant, and applies it to the grid and edge-reversal problems. Compares it with Dijkstra on cost.

Senior: Generalizes to Dial's algorithm with integer buckets and discusses when the log factor matters at scale. Recognizes binary-weight structure hidden in problems such as minimum obstacle removal.

Key points

  • Only for weights 0 and 1
  • 0-edge to the front, 1-edge to the back
  • Deque holds at most two distance values
  • O(V + E)
  • Grid moves along the arrow are free

Common mistakes

  • Using plain BFS and ignoring 0-edges
  • Pushing 0-edges to the back
  • Marking nodes visited on push and missing later improvements
  • Using it with other weights

Follow-ups

  • How would you handle weights 0, 1 and 2 (Dial's buckets)?
  • How do you find the minimum number of edge reversals to reach a node?
  • How would you reconstruct the path?

Tips

  • State the deque invariant
  • Contrast with Dijkstra's log factor
  • Model the grid edges explicitly

Evaluation rubric

  • Correct deque algorithm
  • Correct grid modelling
  • Correct complexity
  • Explains the invariant
75.algorithms-0075Hardsenior

Bellman-Ford basics: compute shortest paths with negative edge weights, detect a reachable negative cycle, and limit routes to at most k edges.

Relax every edge V - 1 times; after round i, every shortest path that uses at most i edges is correct. One extra round that still improves a distance proves a negative cycle reachable from the source. Cost is O(V * E). Relaxing from a copy of the previous round limits paths to one more edge per round, which solves cheapest flights within k stops.

Full answer

Problem

Part 1: given n nodes, directed edges (u, v, w) where w may be negative, and a source, return the shortest distance to every node and whether a negative cycle is reachable from the source.

Part 2: cheapest flight from src to dst using at most k stops (k + 1 edges), or -1.

Example: edges (0,1,4), (0,2,5), (1,2,-3), (2,3,2) from 0 give [0, 4, 1, 3] and no negative cycle. With flights 0-1 100, 1-2 100, 2-3 100, 0-3 500, 1-3 600, the cheapest route from 0 to 3 within 1 stop costs 500, and within 2 stops it costs 300.

Constraints: up to a few thousand nodes and edges (the algorithm is O(V * E)).

Brute force

Enumerate simple paths with DFS and keep the minimum per node: exponential. Dijkstra is not a fallback here, because it can finalise a node too early when a later negative edge would make it cheaper.

Optimal approach

  1. dist[src] = 0, others infinity.
  2. Repeat V - 1 times: for every edge (u, v, w) with dist[u] finite, set dist[v] = min(dist[v], dist[u] + w). Stop early if a round changes nothing.
  3. One more pass: if any edge can still be relaxed, a negative cycle is reachable.

For the k-stops version, run k + 1 rounds, and in each round read from the previous round's array and write into a copy, so that a single round cannot chain several new edges.

Why it works

By induction, after round i every node whose shortest path uses at most i edges has its correct distance, because the last edge of that path was relaxed in round i. Without negative cycles, shortest paths are simple and use at most V - 1 edges, so V - 1 rounds are enough. If a distance still improves afterwards, some path with V or more edges is cheaper, which requires repeating a node, and that repeated loop must have negative total weight.

Complexity

O(V * E) time, O(V) space. The k-stops version is O(k * E) time and O(V) space with two arrays.

Code

python
import random


def bellman_ford(n, edges, src):
    """Shortest paths with negative weights allowed. O(V * E).
    Returns (dist, has_negative_cycle_reachable_from_src)."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(n - 1):               # a shortest simple path has at most n-1 edges
        changed = False
        for u, v, w in edges:
            if dist[u] != INF and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break                        # early exit: already stable
    for u, v, w in edges:                # one more round: any improvement means a negative cycle
        if dist[u] != INF and dist[u] + w < dist[v]:
            return dist, True
    return dist, False


def cheapest_within_k_stops(n, flights, src, dst, k):
    """At most k+1 edges. Relax from a copy each round so one round adds only one edge."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(k + 1):
        nxt = dist[:]
        for u, v, w in flights:
            if dist[u] != INF and dist[u] + w < nxt[v]:
                nxt[v] = dist[u] + w
        dist = nxt
    return -1 if dist[dst] == INF else dist[dst]


def brute(n, edges, src):
    """Enumerate simple paths by DFS (valid reference when no negative cycle exists)."""
    best = [float("inf")] * n
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))

    def walk(u, cost, on_path):
        best[u] = min(best[u], cost)
        for v, w in adj[u]:
            if v not in on_path:
                on_path.add(v)
                walk(v, cost + w, on_path)
                on_path.remove(v)
    walk(src, 0, {src})
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)]
    assert bellman_ford(4, edges, 0) == ([0, 4, 1, 3], False)
    assert bellman_ford(3, [(0, 1, 1), (1, 2, -2), (2, 1, 1)], 0)[1] is True
    assert bellman_ford(3, [(1, 2, -2), (2, 1, 1)], 0)[1] is False   # cycle not reachable from 0
    flights = [(0, 1, 100), (1, 2, 100), (2, 3, 100), (0, 3, 500), (1, 3, 600)]
    assert cheapest_within_k_stops(4, flights, 0, 3, 1) == 500
    assert cheapest_within_k_stops(4, flights, 0, 3, 2) == 300
    assert cheapest_within_k_stops(4, flights, 3, 0, 5) == -1
    rng = random.Random(75)
    tested = 0
    while tested < 300:
        n = rng.randint(1, 7)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(-3, 8)) for _ in range(rng.randint(0, 12))]
        dist, neg = bellman_ford(n, es, 0)
        if not neg:
            assert dist == brute(n, es, 0)
            tested += 1
    print("all tests passed")

Save as b75_bellman_ford.py and run python3 b75_bellman_ford.py. It prints all tests passed (Python 3.13.5).

Edge cases

Negative cycle not reachable from the source (does not affect the answer; the code reports False). Unreachable nodes (skip relaxing from infinity, otherwise inf + negative comparisons cause errors in other languages). Self-loop with negative weight (a negative cycle). Zero edges.

Pattern

Dynamic programming over the number of edges. Related: SPFA (queue-based Bellman-Ford, faster on average but same worst case), currency arbitrage detection (log of rates, negative cycle), difference constraints systems, and Johnson's algorithm, which uses one Bellman-Ford run to reweight edges for Dijkstra.

python
import random


def bellman_ford(n, edges, src):
    """Shortest paths with negative weights allowed. O(V * E).
    Returns (dist, has_negative_cycle_reachable_from_src)."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(n - 1):               # a shortest simple path has at most n-1 edges
        changed = False
        for u, v, w in edges:
            if dist[u] != INF and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break                        # early exit: already stable
    for u, v, w in edges:                # one more round: any improvement means a negative cycle
        if dist[u] != INF and dist[u] + w < dist[v]:
            return dist, True
    return dist, False


def cheapest_within_k_stops(n, flights, src, dst, k):
    """At most k+1 edges. Relax from a copy each round so one round adds only one edge."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(k + 1):
        nxt = dist[:]
        for u, v, w in flights:
            if dist[u] != INF and dist[u] + w < nxt[v]:
                nxt[v] = dist[u] + w
        dist = nxt
    return -1 if dist[dst] == INF else dist[dst]


def brute(n, edges, src):
    """Enumerate simple paths by DFS (valid reference when no negative cycle exists)."""
    best = [float("inf")] * n
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))

    def walk(u, cost, on_path):
        best[u] = min(best[u], cost)
        for v, w in adj[u]:
            if v not in on_path:
                on_path.add(v)
                walk(v, cost + w, on_path)
                on_path.remove(v)
    walk(src, 0, {src})
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)]
    assert bellman_ford(4, edges, 0) == ([0, 4, 1, 3], False)
    assert bellman_ford(3, [(0, 1, 1), (1, 2, -2), (2, 1, 1)], 0)[1] is True
    assert bellman_ford(3, [(1, 2, -2), (2, 1, 1)], 0)[1] is False   # cycle not reachable from 0
    flights = [(0, 1, 100), (1, 2, 100), (2, 3, 100), (0, 3, 500), (1, 3, 600)]
    assert cheapest_within_k_stops(4, flights, 0, 3, 1) == 500
    assert cheapest_within_k_stops(4, flights, 0, 3, 2) == 300
    assert cheapest_within_k_stops(4, flights, 3, 0, 5) == -1
    rng = random.Random(75)
    tested = 0
    while tested < 300:
        n = rng.randint(1, 7)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(-3, 8)) for _ in range(rng.randint(0, 12))]
        dist, neg = bellman_ford(n, es, 0)
        if not neg:
            assert dist == brute(n, es, 0)
            tested += 1
    print("all tests passed")

Bellman-Ford with early exit and negative-cycle check, the k-stops variant, and a simple-path DFS reference used on random graphs with no negative cycle.

Complexity

Time: O(V * E); O(k * E) for k stops. Space: O(V). Early exit helps on typical inputs but does not change the worst case.

By level

Fresher: Explains relaxation and why V - 1 rounds are enough on a small graph with a negative edge. Knows that Dijkstra fails with negative weights.

Mid: Implements negative-cycle detection and the k-stops variant with the copy trick, explaining why in-place updates are wrong there. States O(V * E).

Senior: Discusses SPFA, Johnson's algorithm and difference constraints, and propagating minus infinity to nodes affected by a cycle. Applies negative-cycle detection to arbitrage and constraint checking.

Key points

  • Relax all edges V - 1 times
  • Round i fixes paths with at most i edges
  • Extra improving round means a reachable negative cycle
  • Copy the array per round to limit edges
  • O(V * E)

Common mistakes

  • Using Dijkstra with negative weights
  • Relaxing from infinity
  • Updating in place for the k-stops version
  • Reporting cycles that are not reachable as affecting distances

Follow-ups

  • How do you mark every node whose distance is minus infinity because of a negative cycle?
  • How would you detect currency arbitrage?
  • How does Johnson's algorithm use Bellman-Ford?

Tips

  • State the induction on edge count
  • Explain the copy trick for k stops
  • Mention when to use Dijkstra instead

Evaluation rubric

  • Correct relaxation rounds
  • Correct negative-cycle detection
  • Correct k-stops variant
  • Correct complexity
76.algorithms-0076Mediumfresher

Shortest path in a binary grid: find the fewest cells on a clear path from the top-left to the bottom-right corner, moving in all eight directions.

Each 0-cell is a node connected to its up to eight 0-neighbours, and every move costs 1, so BFS from the top-left gives shortest distances. Return -1 early if either corner is blocked. Store distances in a grid and mark cells when they are enqueued. Time and space are O(R * C).

Full answer

Problem

Given an R x C grid of 0 (open) and 1 (blocked), return the number of cells on the shortest path from (0, 0) to (R-1, C-1) that moves through open cells in any of the 8 directions, or -1 if no path exists.

Example: [[0,1],[1,0]] returns 2 (diagonal step). [[0,0,0],[1,1,0],[1,1,0]] returns 4. A blocked start returns -1.

Constraints: 1 <= R, C <= 100.

Brute force

DFS over all simple paths and keep the shortest: exponential. Repeated relaxation (update every cell from its neighbours until nothing changes) is correct but can take O((R * C)^2).

Optimal approach

  1. If the start or end is blocked, return -1.
  2. dist[0][0] = 1; queue [(0, 0)].
  3. Pop a cell; if it is the target, return its distance. For each of the 8 neighbours inside the grid that is open and unvisited (dist == 0), set dist = dist + 1 and enqueue.
  4. If the queue empties, return -1.

Why it works

All moves have equal cost, so BFS visits cells in order of path length; the first time the target is popped, its distance is the shortest. Using the distance grid as the visited marker ensures each cell is enqueued once.

Complexity

O(R * C) time (each cell processed once with 8 neighbour checks) and O(R * C) space.

Code

python
import random
from collections import deque


def shortest_path_binary_matrix(grid):
    """Length (in cells) of the shortest clear path from top-left to bottom-right,
    moving in 8 directions through 0-cells. -1 if none. BFS: O(R * C)."""
    n, m = len(grid), len(grid[0])
    if grid[0][0] or grid[n - 1][m - 1]:
        return -1
    dist = [[0] * m for _ in range(n)]
    dist[0][0] = 1
    q = deque([(0, 0)])
    while q:
        r, c = q.popleft()
        if (r, c) == (n - 1, m - 1):
            return dist[r][c]
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and dist[nr][nc] == 0:
                    dist[nr][nc] = dist[r][c] + 1
                    q.append((nr, nc))
    return -1


def brute(grid):
    """Repeated relaxation until nothing changes (slow but obviously correct)."""
    n, m = len(grid), len(grid[0])
    INF = float("inf")
    d = [[INF] * m for _ in range(n)]
    if grid[0][0] == 0:
        d[0][0] = 1
    changed = True
    while changed:
        changed = False
        for r in range(n):
            for c in range(m):
                if grid[r][c] or d[r][c] == INF:
                    continue
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and d[r][c] + 1 < d[nr][nc]:
                            d[nr][nc] = d[r][c] + 1
                            changed = True
    return -1 if d[-1][-1] == INF else d[-1][-1]


if __name__ == "__main__":
    assert shortest_path_binary_matrix([[0, 1], [1, 0]]) == 2
    assert shortest_path_binary_matrix([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) == 4
    assert shortest_path_binary_matrix([[1, 0, 0], [1, 1, 0], [1, 1, 0]]) == -1
    assert shortest_path_binary_matrix([[0]]) == 1
    rng = random.Random(76)
    for _ in range(500):
        n, m = rng.randint(1, 6), rng.randint(1, 6)
        g = [[int(rng.random() < 0.3) for _ in range(m)] for _ in range(n)]
        assert shortest_path_binary_matrix(g) == brute(g)
    print("all tests passed")

Save as b76_grid_shortest_path.py and run python3 b76_grid_shortest_path.py. It prints all tests passed (Python 3.13.5).

Edge cases

1 x 1 grid with an open cell (answer 1). Start or end blocked. Single row or column. Counting cells versus steps (this problem counts cells, so the start contributes 1).

Pattern

BFS on an implicit grid graph. Changing the neighbour set or costs gives related problems: 4-direction mazes, knight moves on a board, multi-source BFS (nearest gate, rotting oranges), 0-1 BFS when some moves are free, and A* with a Chebyshev distance heuristic for large open grids.

python
import random
from collections import deque


def shortest_path_binary_matrix(grid):
    """Length (in cells) of the shortest clear path from top-left to bottom-right,
    moving in 8 directions through 0-cells. -1 if none. BFS: O(R * C)."""
    n, m = len(grid), len(grid[0])
    if grid[0][0] or grid[n - 1][m - 1]:
        return -1
    dist = [[0] * m for _ in range(n)]
    dist[0][0] = 1
    q = deque([(0, 0)])
    while q:
        r, c = q.popleft()
        if (r, c) == (n - 1, m - 1):
            return dist[r][c]
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and dist[nr][nc] == 0:
                    dist[nr][nc] = dist[r][c] + 1
                    q.append((nr, nc))
    return -1


def brute(grid):
    """Repeated relaxation until nothing changes (slow but obviously correct)."""
    n, m = len(grid), len(grid[0])
    INF = float("inf")
    d = [[INF] * m for _ in range(n)]
    if grid[0][0] == 0:
        d[0][0] = 1
    changed = True
    while changed:
        changed = False
        for r in range(n):
            for c in range(m):
                if grid[r][c] or d[r][c] == INF:
                    continue
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and d[r][c] + 1 < d[nr][nc]:
                            d[nr][nc] = d[r][c] + 1
                            changed = True
    return -1 if d[-1][-1] == INF else d[-1][-1]


if __name__ == "__main__":
    assert shortest_path_binary_matrix([[0, 1], [1, 0]]) == 2
    assert shortest_path_binary_matrix([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) == 4
    assert shortest_path_binary_matrix([[1, 0, 0], [1, 1, 0], [1, 1, 0]]) == -1
    assert shortest_path_binary_matrix([[0]]) == 1
    rng = random.Random(76)
    for _ in range(500):
        n, m = rng.randint(1, 6), rng.randint(1, 6)
        g = [[int(rng.random() < 0.3) for _ in range(m)] for _ in range(n)]
        assert shortest_path_binary_matrix(g) == brute(g)
    print("all tests passed")

8-direction BFS with a distance grid, cross-checked against repeated relaxation on random grids.

Complexity

Time: O(R * C). Space: O(R * C). A* with the Chebyshev heuristic explores fewer cells on open grids but has the same worst case.

By level

Fresher: Models the grid as a graph and runs BFS with 8 neighbour offsets. Handles blocked corners and counts cells correctly.

Mid: Explains why BFS order guarantees the shortest path and reconstructs the path with parents. Adapts to weighted cells with Dijkstra.

Senior: Discusses A* heuristics, bidirectional search for large maps, and precomputation for repeated queries on static maps. Considers memory use for very large grids.

Key points

  • Grid cells are nodes, moves are unit edges
  • BFS gives shortest paths for unit costs
  • Check blocked corners first
  • Use the distance grid as visited
  • Count cells or steps as the problem says

Common mistakes

  • Using DFS for shortest paths
  • Forgetting diagonal moves
  • Off-by-one between cells and steps
  • Marking visited on dequeue and enqueueing cells many times

Follow-ups

  • How would A* speed this up?
  • How do you return the path itself?
  • What changes if some cells cost more to enter?

Tips

  • Clarify allowed moves
  • State why BFS is correct here
  • Handle blocked corners before searching

Evaluation rubric

  • Correct BFS
  • Correct neighbour set
  • Correct edge cases
  • Correct complexity
77.algorithms-0077Hardsenior

Shortest path in a grid with up to k obstacle removals: compute the fewest steps from corner to corner when you may break through at most k walls.

Search over states (row, col, removals left) instead of cells, since reaching a cell with more removals left is strictly better. BFS by steps finds the minimum, and keeping the best removals-left per cell prunes dominated states. If k >= R + C - 2, the Manhattan path is always possible. Time O(R * C * k), space O(R * C * k) in the worst case.

Full answer

Problem

Given an R x C grid of 0 (empty) and 1 (wall) and an integer k, return the minimum number of 4-directional steps from (0, 0) to (R-1, C-1) when up to k walls may be removed along the way, or -1 if impossible. Start and end are empty.

Example: for

0 0 0 1 1 0 0 0 0 0 1 1 0 0 0

with k = 1, the answer is 6 (break the wall at (3, 2)). For [[0,1,1],[1,1,1],[1,0,0]] with k = 1 the answer is -1.

Constraints: 1 <= R, C <= 40, 1 <= k <= R * C.

Brute force

Try every set of at most k walls to remove and run BFS on each modified grid: O(C(W, k) * R * C) for W walls, exponential in k.

Optimal approach

BFS where a state is (r, c, left):

  1. Shortcut: if k >= R + C - 2, return R + C - 2.
  2. Start with (0, 0, k) at 0 steps.
  3. From a state, move to each neighbour; entering a wall reduces left by 1. Skip if left would be negative.
  4. Keep best_left[r][c], the most removals left with which the cell was reached. Only enqueue a new state when it beats that value.
  5. Return the step count when the target is popped.

Why it works

The extra coordinate makes the problem a plain unweighted shortest path over states, so BFS returns the minimum steps. The pruning is safe because BFS processes states in non-decreasing step order: a later visit to the same cell has at least as many steps, so it is only useful if it has strictly more removals left. The Manhattan shortcut holds because a monotone path has R + C - 2 steps and at most R + C - 3 interior cells.

Complexity

O(R * C * k) states, each with 4 moves: O(R * C * k) time and space in the worst case. The shortcut caps k at R + C - 3 effective values, so the bound is also O(R * C * (R + C)).

Code

python
import random
from collections import deque
from itertools import combinations


def shortest_with_k_removals(grid, k):
    """Fewest 4-directional steps from top-left to bottom-right when up to k walls (1s)
    may be removed. BFS over states (row, col, removals_left). O(R * C * k)."""
    n, m = len(grid), len(grid[0])
    if k >= n + m - 2:
        return n + m - 2                 # enough removals to walk the Manhattan path
    best_left = [[-1] * m for _ in range(n)]   # most removals left seen at each cell
    best_left[0][0] = k
    q = deque([(0, 0, k, 0)])
    while q:
        r, c, left, steps = q.popleft()
        if (r, c) == (n - 1, m - 1):
            return steps
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < n and 0 <= nc < m:
                nl = left - grid[nr][nc]
                if nl > best_left[nr][nc]:     # dominates every earlier visit with fewer removals left
                    best_left[nr][nc] = nl
                    q.append((nr, nc, nl, steps + 1))
    return -1


def brute(grid, k):
    """Try every set of at most k removed walls, run plain BFS on each."""
    n, m = len(grid), len(grid[0])
    walls = [(r, c) for r in range(n) for c in range(m) if grid[r][c]]
    best = -1
    for t in range(min(k, len(walls)) + 1):
        for removed in combinations(walls, t):
            rem = set(removed)
            if grid[0][0] and (0, 0) not in rem:
                continue
            dist = {(0, 0): 0}
            q = deque([(0, 0)])
            while q:
                r, c = q.popleft()
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= nr < n and 0 <= nc < m and (nr, nc) not in dist and (grid[nr][nc] == 0 or (nr, nc) in rem):
                        dist[(nr, nc)] = dist[(r, c)] + 1
                        q.append((nr, nc))
            d = dist.get((n - 1, m - 1))
            if d is not None and (best == -1 or d < best):
                best = d
    return best


if __name__ == "__main__":
    g = [[0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 0]]
    assert shortest_with_k_removals(g, 1) == 6
    assert shortest_with_k_removals([[0, 1, 1], [1, 1, 1], [1, 0, 0]], 1) == -1
    assert shortest_with_k_removals([[0]], 0) == 0
    rng = random.Random(77)
    for _ in range(300):
        n, m = rng.randint(1, 4), rng.randint(1, 4)
        grid = [[int(rng.random() < 0.4) for _ in range(m)] for _ in range(n)]
        grid[0][0] = grid[-1][-1] = 0
        k = rng.randint(0, 2)
        assert shortest_with_k_removals(grid, k) == brute(grid, k)
    print("all tests passed")

Save as b77_grid_obstacle_elimination.py and run python3 b77_grid_obstacle_elimination.py. It prints all tests passed (Python 3.13.5).

Edge cases

k = 0 (plain BFS). Single-cell grid (0 steps). k large enough for the shortcut. Walls everywhere except the corners. A visited set on (r, c) alone is wrong because it discards a state with more removals left.

Pattern

BFS on an expanded state space: add whatever resource or flag changes future options to the node identity. Same idea: keys and doors (bitmask of keys), shortest path visiting all nodes (bitmask of visited), fuel-limited routes, and the k-stops flight problem.

python
import random
from collections import deque
from itertools import combinations


def shortest_with_k_removals(grid, k):
    """Fewest 4-directional steps from top-left to bottom-right when up to k walls (1s)
    may be removed. BFS over states (row, col, removals_left). O(R * C * k)."""
    n, m = len(grid), len(grid[0])
    if k >= n + m - 2:
        return n + m - 2                 # enough removals to walk the Manhattan path
    best_left = [[-1] * m for _ in range(n)]   # most removals left seen at each cell
    best_left[0][0] = k
    q = deque([(0, 0, k, 0)])
    while q:
        r, c, left, steps = q.popleft()
        if (r, c) == (n - 1, m - 1):
            return steps
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < n and 0 <= nc < m:
                nl = left - grid[nr][nc]
                if nl > best_left[nr][nc]:     # dominates every earlier visit with fewer removals left
                    best_left[nr][nc] = nl
                    q.append((nr, nc, nl, steps + 1))
    return -1


def brute(grid, k):
    """Try every set of at most k removed walls, run plain BFS on each."""
    n, m = len(grid), len(grid[0])
    walls = [(r, c) for r in range(n) for c in range(m) if grid[r][c]]
    best = -1
    for t in range(min(k, len(walls)) + 1):
        for removed in combinations(walls, t):
            rem = set(removed)
            if grid[0][0] and (0, 0) not in rem:
                continue
            dist = {(0, 0): 0}
            q = deque([(0, 0)])
            while q:
                r, c = q.popleft()
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= nr < n and 0 <= nc < m and (nr, nc) not in dist and (grid[nr][nc] == 0 or (nr, nc) in rem):
                        dist[(nr, nc)] = dist[(r, c)] + 1
                        q.append((nr, nc))
            d = dist.get((n - 1, m - 1))
            if d is not None and (best == -1 or d < best):
                best = d
    return best


if __name__ == "__main__":
    g = [[0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 0]]
    assert shortest_with_k_removals(g, 1) == 6
    assert shortest_with_k_removals([[0, 1, 1], [1, 1, 1], [1, 0, 0]], 1) == -1
    assert shortest_with_k_removals([[0]], 0) == 0
    rng = random.Random(77)
    for _ in range(300):
        n, m = rng.randint(1, 4), rng.randint(1, 4)
        grid = [[int(rng.random() < 0.4) for _ in range(m)] for _ in range(n)]
        grid[0][0] = grid[-1][-1] = 0
        k = rng.randint(0, 2)
        assert shortest_with_k_removals(grid, k) == brute(grid, k)
    print("all tests passed")

State-space BFS with best-removals-left pruning and the Manhattan shortcut; random grids are checked by trying every subset of removed walls.

Complexity

Time: O(R * C * k). Space: O(R * C * k) worst case. With pruning, typical runs explore far fewer states; the shortcut bounds effective k by R + C - 3.

By level

Fresher: Explains why tracking only cells fails, using a small grid where a path with more removals left matters. Writes BFS over (row, col, left).

Mid: Adds the best-left pruning and the Manhattan shortcut and argues why both are safe. States the state-space complexity.

Senior: Generalizes state expansion to keys, fuel and visited-set bitmasks and estimates state counts before choosing the method. Discusses A* with Manhattan distance and memory limits on larger grids.

Key points

  • State = (row, col, removals left)
  • BFS over states gives minimum steps
  • Prune states with fewer removals left than seen
  • Manhattan shortcut when k is large
  • Visited on cells alone is wrong

Common mistakes

  • Using a visited set keyed only by cell
  • Decrementing k when entering empty cells
  • Missing the large-k shortcut and timing out
  • Using DFS for a shortest path

Follow-ups

  • How would you solve a maze with keys and doors?
  • What if removing a wall costs differently per wall?
  • How would A* help here?

Tips

  • Explain why the state must include k
  • Justify the pruning with BFS order
  • Mention the shortcut early

Evaluation rubric

  • Correct state definition
  • Correct pruning argument
  • Correct complexity
  • Handles edge cases
78.algorithms-0078Easyfresher

Climbing stairs: count the distinct ways to reach step n when each move climbs 1 or 2 steps, and generalize to any set of allowed step sizes.

The last move into step n came from n - 1 or n - 2, so ways(n) = ways(n - 1) + ways(n - 2) with ways(0) = ways(1) = 1. That is the Fibonacci recurrence, computed bottom-up in O(n) time and O(1) space. Plain recursion recomputes subproblems and is O(2^n). For a step set S, ways(i) sums ways(i - s) over s in S.

Full answer

Problem

You are at step 0 and want to reach step n. Each move climbs 1 or 2 steps. Return the number of distinct move sequences.

Example: n = 3 gives 3 (1+1+1, 1+2, 2+1); n = 5 gives 8.

Constraints: 0 <= n <= 90 here (results stay exact in Python; in 64-bit languages n = 92 is the overflow limit).

Brute force

Recursion straight from the definition: ways(n) = ways(n-1) + ways(n-2). The call tree doubles at each level, so it is O(2^n) (more precisely O(phi^n)), because ways(n-2) is recomputed inside ways(n-1).

Optimal approach

Bottom-up with two variables: start with a = ways(0) = 1 and b = ways(1) = 1, then repeat a, b = b, a + b until reaching n.

Generalization: for an allowed step set S, fill ways[0..n] with ways[0] = 1 and ways[i] = sum(ways[i - s] for s in S if s <= i).

Why it works

Every sequence that reaches step n ends with exactly one last move. Grouping sequences by that last move splits them into disjoint groups: those ending with a 1-step (each one is a way to reach n - 1) and those ending with a 2-step (a way to reach n - 2). Adding the group sizes counts each sequence once. Each value depends only on the two before it, so two variables are enough.

Complexity

O(n) time and O(1) space for the 1-or-2 version; O(n * |S|) time and O(n) space for a general step set. Matrix exponentiation of [[1,1],[1,0]] gives O(log n) arithmetic operations if n is huge.

Code

python
from functools import lru_cache


def climb(n):
    """Ways to climb n steps taking 1 or 2 at a time. ways(n) = ways(n-1) + ways(n-2). O(n), O(1)."""
    a, b = 1, 1                          # ways(0), ways(1)
    for _ in range(n - 1):
        a, b = b, a + b
    return b if n >= 1 else 1


def climb_steps(n, steps):
    """General step set, e.g. {1, 3, 5}. O(n * len(steps)) time, O(n) space."""
    ways = [1] + [0] * n
    for i in range(1, n + 1):
        ways[i] = sum(ways[i - s] for s in steps if s <= i)
    return ways[n]


def brute(n):
    """Plain recursion: O(2^n). Only for small n."""
    if n <= 1:
        return 1
    return brute(n - 1) + brute(n - 2)


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


if __name__ == "__main__":
    assert [climb(n) for n in range(1, 7)] == [1, 2, 3, 5, 8, 13]
    assert climb(0) == 1                             # one way: do nothing
    assert all(climb(n) == brute(n) == memo(n) == climb_steps(n, (1, 2)) for n in range(0, 22))
    assert climb_steps(4, (1, 3)) == 3               # 1111, 13, 31
    assert climb(90) == 4660046610375530309          # Python ints do not overflow
    print("all tests passed")

Save as b78_climbing_stairs.py and run python3 b78_climbing_stairs.py. It prints all tests passed (Python 3.13.5).

Edge cases

n = 0 (one way: no moves). n = 1 (one way). Large n (overflow in fixed-width languages; ask for a modulus). Step sets that include sizes larger than n.

Pattern

The basic DP template: define the state (ways to reach i), find the transition from the last decision, set base cases, and roll the table down to O(1) when only a few previous states matter. The same shape gives decode ways, tiling a 2 x n board, and min cost climbing stairs.

python
from functools import lru_cache


def climb(n):
    """Ways to climb n steps taking 1 or 2 at a time. ways(n) = ways(n-1) + ways(n-2). O(n), O(1)."""
    a, b = 1, 1                          # ways(0), ways(1)
    for _ in range(n - 1):
        a, b = b, a + b
    return b if n >= 1 else 1


def climb_steps(n, steps):
    """General step set, e.g. {1, 3, 5}. O(n * len(steps)) time, O(n) space."""
    ways = [1] + [0] * n
    for i in range(1, n + 1):
        ways[i] = sum(ways[i - s] for s in steps if s <= i)
    return ways[n]


def brute(n):
    """Plain recursion: O(2^n). Only for small n."""
    if n <= 1:
        return 1
    return brute(n - 1) + brute(n - 2)


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


if __name__ == "__main__":
    assert [climb(n) for n in range(1, 7)] == [1, 2, 3, 5, 8, 13]
    assert climb(0) == 1                             # one way: do nothing
    assert all(climb(n) == brute(n) == memo(n) == climb_steps(n, (1, 2)) for n in range(0, 22))
    assert climb_steps(4, (1, 3)) == 3               # 1111, 13, 31
    assert climb(90) == 4660046610375530309          # Python ints do not overflow
    print("all tests passed")

Two-variable loop, a general step-set table, memoized and plain recursion for comparison; all agree for n up to 21.

Complexity

Time: O(n). Space: O(1). General step sets cost O(n * |S|) time with an O(n) table.

By level

Fresher: Derives the recurrence from the last move and writes the bottom-up loop. Explains why the naive recursion repeats work.

Mid: Generalizes to any step set and to broken steps, and reduces space to O(1) where possible. Discusses overflow and modular answers.

Senior: Uses matrix exponentiation for very large n and explains the linear recurrence view. Connects the counting template to path counting on DAGs.

Key points

  • Group sequences by their last move
  • ways(n) = ways(n-1) + ways(n-2)
  • Base cases ways(0) = ways(1) = 1
  • Two variables replace the table
  • Plain recursion is exponential

Common mistakes

  • Wrong base case for n = 0
  • Using plain recursion without memoization
  • Off-by-one in the loop count
  • Ignoring overflow in fixed-width languages

Follow-ups

  • How would you compute this for n = 10^18 modulo a prime?
  • What if some steps are broken and cannot be used?
  • What if each step has a cost and you want the minimum cost?

Tips

  • Derive the recurrence from the last move
  • Show the exponential call tree briefly
  • Roll the table to O(1) space

Evaluation rubric

  • Correct recurrence and base cases
  • O(n) solution
  • Explains why recursion is slow
  • Generalizes to other step sets
79.algorithms-0079Mediumfresher

House robber: choose houses along a street to maximise the total money taken when two neighbouring houses cannot both be chosen, then solve it for houses arranged in a circle.

For each house decide to take it (add its value to the best answer two houses back) or skip it (keep the best answer one house back): best(i) = max(best(i-1), best(i-2) + nums[i]). Two running variables give O(n) time and O(1) space. In a circle the first and last houses are adjacent, so solve the line twice, once without the first house and once without the last, and take the larger.

Full answer

Problem

Given non-negative values nums for houses in a row, return the largest sum of values you can take without taking two adjacent houses. Then solve it when the houses form a circle.

Example: [2, 7, 9, 3, 1] gives 12 (2 + 9 + 1). In a circle, [2, 3, 2] gives 3, because the two 2s are neighbours.

Constraints: 1 <= n <= 100 (larger is fine), values from 0 to 400.

Brute force

Try every subset with no two adjacent houses: there are Fibonacci(n) such subsets, so the cost grows exponentially (about 1.6^n).

Optimal approach

Keep prev2 (best up to house i - 2) and prev1 (best up to house i - 1). For each value x: prev2, prev1 = prev1, max(prev1, prev2 + x). The answer is prev1.

Circle: if there is one house, return its value. Otherwise return max(rob(nums[1:]), rob(nums[:-1])).

Why it works

Consider the best plan for the first i houses. Either it skips house i, in which case it is the best plan for the first i - 1 houses, or it takes house i, in which case house i - 1 is excluded and the rest is the best plan for the first i - 2. Taking the max of the two covers every option. For the circle, any valid plan leaves out the first house or the last house (or both), so one of the two line problems contains it.

Complexity

O(n) time and O(1) space; the circle version runs the line version twice.

Code

python
import random
from itertools import product


def rob(nums):
    """Max sum with no two adjacent houses. best(i) = max(best(i-1), best(i-2) + nums[i]). O(n), O(1)."""
    prev2, prev1 = 0, 0                  # best up to i-2, best up to i-1
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1


def rob_circle(nums):
    """Houses in a circle: first and last are adjacent. Solve twice, skipping one end each time."""
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[1:]), rob(nums[:-1]))


def brute(nums, circle=False):
    best = 0
    n = len(nums)
    for pick in product((0, 1), repeat=n):
        if any(pick[i] and pick[i + 1] for i in range(n - 1)):
            continue
        if circle and n > 1 and pick[0] and pick[-1]:
            continue
        best = max(best, sum(x for x, p in zip(nums, pick) if p))
    return best


if __name__ == "__main__":
    assert rob([1, 2, 3, 1]) == 4
    assert rob([2, 7, 9, 3, 1]) == 12
    assert rob([]) == 0 and rob([5]) == 5
    assert rob_circle([2, 3, 2]) == 3 and rob_circle([1, 2, 3, 1]) == 4
    rng = random.Random(79)
    for _ in range(1000):
        a = [rng.randint(0, 20) for _ in range(rng.randint(1, 10))]
        assert rob(a) == brute(a)
        assert rob_circle(a) == brute(a, circle=True)
    print("all tests passed")

Save as b79_house_robber.py and run python3 b79_house_robber.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list (0). One house (its value). Two houses (the larger). All zeros. The circular single-house case must not slice away the only house.

Pattern

Take-or-skip DP over a sequence with a "no two adjacent" constraint. Related: delete and earn (reduce to house robber over values), maximum sum of non-adjacent elements, the tree version (return a pair "with root" and "without root" per node), and paint fence problems.

python
import random
from itertools import product


def rob(nums):
    """Max sum with no two adjacent houses. best(i) = max(best(i-1), best(i-2) + nums[i]). O(n), O(1)."""
    prev2, prev1 = 0, 0                  # best up to i-2, best up to i-1
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1


def rob_circle(nums):
    """Houses in a circle: first and last are adjacent. Solve twice, skipping one end each time."""
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[1:]), rob(nums[:-1]))


def brute(nums, circle=False):
    best = 0
    n = len(nums)
    for pick in product((0, 1), repeat=n):
        if any(pick[i] and pick[i + 1] for i in range(n - 1)):
            continue
        if circle and n > 1 and pick[0] and pick[-1]:
            continue
        best = max(best, sum(x for x, p in zip(nums, pick) if p))
    return best


if __name__ == "__main__":
    assert rob([1, 2, 3, 1]) == 4
    assert rob([2, 7, 9, 3, 1]) == 12
    assert rob([]) == 0 and rob([5]) == 5
    assert rob_circle([2, 3, 2]) == 3 and rob_circle([1, 2, 3, 1]) == 4
    rng = random.Random(79)
    for _ in range(1000):
        a = [rng.randint(0, 20) for _ in range(rng.randint(1, 10))]
        assert rob(a) == brute(a)
        assert rob_circle(a) == brute(a, circle=True)
    print("all tests passed")

Rolling two-variable DP for a line and the two-run reduction for a circle, checked against all subsets on random inputs.

Complexity

Time: O(n). Space: O(1). The circular version is two linear passes over slices; index bounds avoid copying if needed.

By level

Fresher: Writes the take-or-skip recurrence and traces it on a short list. Explains why picking every other house is not always best.

Mid: Solves the circle version with two passes and reconstructs the chosen houses. Extends the idea to the tree version with paired values.

Senior: Generalizes to constraint-separated selections such as k-gap rules and weighted interval scheduling. Discusses how the recurrence maps to a small state machine, which helps derive similar DPs quickly.

Key points

  • best(i) = max(skip, take)
  • Take means adding to best(i - 2)
  • Two variables are enough
  • Circle: drop the first or drop the last
  • Handle n = 1 separately in the circle

Common mistakes

  • Greedy choice of the largest values
  • Alternating even and odd indices only
  • Forgetting the n = 1 case in the circle
  • Off-by-one in the rolling update

Follow-ups

  • How would you solve it on a binary tree?
  • How would you return which houses were chosen?
  • How does delete and earn reduce to this?

Tips

  • State the take-or-skip choice in one sentence
  • Explain the circle reduction
  • Show a counterexample to the even/odd idea

Evaluation rubric

  • Correct recurrence
  • O(1) space
  • Correct circle handling
  • Edge cases
80.algorithms-0080Mediummid

Coin change: find the fewest coins that make a target amount with unlimited coins of each denomination, explain why greedy fails, and count the number of combinations.

Let dp[a] be the fewest coins for amount a: dp[0] = 0 and dp[a] = 1 + min(dp[a - c]) over coins c <= a. Filling a from 1 to the target takes O(amount * coins) time and O(amount) space; an unreachable amount stays at the sentinel and returns -1. Greedy (largest coin first) fails for coins like [1, 3, 4] and amount 6. Counting combinations puts coins in the outer loop so each combination is counted once.

Full answer

Problem

Given coin values and an amount, return the fewest coins that sum to the amount (each coin may be used any number of times), or -1 if impossible. Follow-up: return the number of combinations that make the amount.

Example: coins [1, 2, 5], amount 11 returns 3 (5 + 5 + 1). Coins [2], amount 3 returns -1. Coins [1, 3, 4], amount 6 returns 2 (3 + 3), while greedy picks 4 + 1 + 1. Coins [1, 2, 5] have 4 combinations for amount 5.

Constraints: 1 <= len(coins) <= 12, coin values up to 2^31 - 1, 0 <= amount <= 10^4.

Brute force

Recursively try every coin at every step: f(a) = 1 + min(f(a - c)). Without memoization the branching factor is the number of coins and the depth is up to the amount, which is exponential.

BFS over remaining amounts is a valid alternative: each level adds one coin, so the first time 0 is reached gives the answer; it is used as the reference in the tests.

Optimal approach

Bottom-up table:

  1. dp = [0] + [INF] * amount with INF = amount + 1 (more coins than could ever be needed).
  2. For a in 1..amount, for each coin c <= a: dp[a] = min(dp[a], dp[a - c] + 1).
  3. Return dp[amount] if it is below INF, else -1.

Counting combinations: ways = [1] + [0] * amount; for each coin c (outer loop), for a in c..amount: ways[a] += ways[a - c].

Why it works

Any optimal way to make a ends with some last coin c, and the rest is an optimal way to make a - c (otherwise swapping in a better one would improve the total). So taking the minimum over all possible last coins gives the answer, and amounts are filled in increasing order so every dp[a - c] is ready. For counting, processing coin by coin means each combination is built in a fixed coin order, so 1 + 2 and 2 + 1 are the same entry.

Complexity

O(amount * len(coins)) time and O(amount) space for both versions. This is pseudo-polynomial: it depends on the numeric value of the amount, not the input length.

Code

python
import random
from collections import deque


def coin_change(coins, amount):
    """Fewest coins to make amount, or -1. Unbounded supply. O(amount * len(coins)) time, O(amount) space."""
    INF = amount + 1
    dp = [0] + [INF] * amount            # dp[a] = fewest coins for a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[amount] if dp[amount] < INF else -1


def count_ways(coins, amount):
    """Number of combinations (order ignored). Coins in the outer loop avoids counting 1+2 and 2+1 twice."""
    ways = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            ways[a] += ways[a - c]
    return ways[amount]


def greedy(coins, amount):
    """Largest coin first. Correct for some coin systems only."""
    n = 0
    for c in sorted(coins, reverse=True):
        n += amount // c
        amount %= c
    return n if amount == 0 else -1


def brute_bfs(coins, amount):
    """BFS over remaining amounts: the first time 0 is reached uses the fewest coins."""
    seen, q = {amount}, deque([(amount, 0)])
    while q:
        a, k = q.popleft()
        if a == 0:
            return k
        for c in coins:
            if a - c >= 0 and a - c not in seen:
                seen.add(a - c)
                q.append((a - c, k + 1))
    return -1


if __name__ == "__main__":
    assert coin_change([1, 2, 5], 11) == 3
    assert coin_change([2], 3) == -1
    assert coin_change([1], 0) == 0
    assert coin_change([1, 3, 4], 6) == 2 and greedy([1, 3, 4], 6) == 3   # greedy gives 4+1+1
    assert count_ways([1, 2, 5], 5) == 4
    rng = random.Random(80)
    for _ in range(500):
        coins = rng.sample(range(1, 15), rng.randint(1, 4))
        amt = rng.randint(0, 60)
        assert coin_change(coins, amt) == brute_bfs(coins, amt)
    print("all tests passed")

Save as b80_coin_change.py and run python3 b80_coin_change.py. It prints all tests passed (Python 3.13.5).

Edge cases

Amount 0 (0 coins, 1 combination). No combination possible (-1). Coins larger than the amount (skipped). Duplicate coin values. Greedy works for canonical systems such as [1, 5, 10, 25] but not in general.

Pattern

Unbounded knapsack: each item can be used repeatedly, so the inner loop over amounts runs upward. Swapping the loop order changes what is counted (permutations versus combinations). Related problems: perfect squares, minimum cost tickets, and integer break.

python
import random
from collections import deque


def coin_change(coins, amount):
    """Fewest coins to make amount, or -1. Unbounded supply. O(amount * len(coins)) time, O(amount) space."""
    INF = amount + 1
    dp = [0] + [INF] * amount            # dp[a] = fewest coins for a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[amount] if dp[amount] < INF else -1


def count_ways(coins, amount):
    """Number of combinations (order ignored). Coins in the outer loop avoids counting 1+2 and 2+1 twice."""
    ways = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            ways[a] += ways[a - c]
    return ways[amount]


def greedy(coins, amount):
    """Largest coin first. Correct for some coin systems only."""
    n = 0
    for c in sorted(coins, reverse=True):
        n += amount // c
        amount %= c
    return n if amount == 0 else -1


def brute_bfs(coins, amount):
    """BFS over remaining amounts: the first time 0 is reached uses the fewest coins."""
    seen, q = {amount}, deque([(amount, 0)])
    while q:
        a, k = q.popleft()
        if a == 0:
            return k
        for c in coins:
            if a - c >= 0 and a - c not in seen:
                seen.add(a - c)
                q.append((a - c, k + 1))
    return -1


if __name__ == "__main__":
    assert coin_change([1, 2, 5], 11) == 3
    assert coin_change([2], 3) == -1
    assert coin_change([1], 0) == 0
    assert coin_change([1, 3, 4], 6) == 2 and greedy([1, 3, 4], 6) == 3   # greedy gives 4+1+1
    assert count_ways([1, 2, 5], 5) == 4
    rng = random.Random(80)
    for _ in range(500):
        coins = rng.sample(range(1, 15), rng.randint(1, 4))
        amt = rng.randint(0, 60)
        assert coin_change(coins, amt) == brute_bfs(coins, amt)
    print("all tests passed")

Minimum-coins table, combination count, the greedy counterexample, and a BFS reference on random coin sets.

Complexity

Time: O(amount * len(coins)). Space: O(amount). Pseudo-polynomial in the amount; BFS has the same bound but often stops early.

By level

Fresher: Writes the bottom-up table and shows with a counterexample why greedy is wrong. Handles the -1 case.

Mid: Adds the combinations count with the correct loop order and reconstructs the coins used. Explains the pseudo-polynomial bound.

Senior: Discusses when canonical coin systems allow greedy, memory for very large amounts, and BFS as an early-exit alternative. Relates the problem to unbounded knapsack and change-making in payment systems.

Key points

  • dp[a] = 1 + min over coins of dp[a - c]
  • Sentinel amount + 1 marks unreachable
  • Greedy fails for non-canonical coins
  • Coins in the outer loop count combinations
  • Pseudo-polynomial time

Common mistakes

  • Trusting greedy
  • Using float('inf') and then returning it
  • Swapping loops and counting permutations instead of combinations
  • Forgetting amount 0

Follow-ups

  • How would you return the actual coins used?
  • How do you count ordered sequences instead of combinations?
  • What if each coin can be used at most once?

Tips

  • Show the [1, 3, 4] counterexample
  • Explain the loop order for counting
  • Mention pseudo-polynomial time

Evaluation rubric

  • Correct DP
  • Handles impossible amounts
  • Explains greedy failure
  • Correct counting variant