← Interview prep

Algorithms interview questions

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

100 questions · Page 3 of 5

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

Page 3 of 5

Questions 41–60 of 100 · 0 of 20 on this page marked learned

41.algorithms-0041Hardsenior

Merge k sorted linked lists into one sorted list in O(N log k) time, where N is the total number of nodes.

Put the head of each list in a min-heap keyed by value. Repeatedly pop the smallest node, attach it to the output and push that node's successor. The heap never holds more than k nodes, so each of the N steps costs O(log k). Pairwise divide-and-conquer merging gives the same O(N log k) bound without a heap.

Full answer

Problem

Given k sorted linked lists, merge them into one sorted list by relinking nodes, and return its head.

Example: [1 -> 4 -> 5, 1 -> 3 -> 4, 2 -> 6] gives 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6.

Constraints: 0 <= k <= 10^4, total nodes N <= 10^4, any list may be empty.

Brute force

Collect all values, sort them and build a new list: O(N log N) time, O(N) extra space.

Merging lists one at a time into a growing result: the result is re-scanned each time, O(N x k) in total.

Optimal approach

  1. Push (node.val, i, node) for each non-empty list head. The index i breaks ties so Python never compares two ListNode objects (which would raise TypeError).
  2. Use a dummy head and a tail pointer.
  3. While the heap is not empty: pop the smallest, attach it, and push its next if it exists.

Alternative: divide and conquer. Merge lists in pairs (0 with 1, 2 with 3, ...), then merge the results, for log k rounds of O(N) work each. The code includes merge_two, the building block.

Why it works

The smallest remaining node overall must be the head of one of the remaining lists, because each list is sorted. The heap holds exactly those heads, so popping its minimum always gives the next node of the output. Pushing the successor keeps the heap equal to the set of current heads.

Complexity

O(N log k) time. O(k) extra space for the heap; output reuses the existing nodes.

Code

python
import heapq


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


def from_list(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


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


def merge_two(a, b):
    """Merge two sorted lists by relinking nodes. O(len(a) + len(b))."""
    dummy = tail = ListNode(0)
    while a and b:
        if a.val <= b.val:          # <= keeps the merge stable
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next


def merge_k_lists(lists):
    """Merge k sorted lists with a min-heap of the current heads. O(N log k)."""
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)              # i breaks ties so nodes are never compared
    dummy = tail = ListNode(0)
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


if __name__ == "__main__":
    assert to_list(merge_two(from_list([1, 2, 4]), from_list([1, 3, 4]))) == [1, 1, 2, 3, 4, 4]
    assert to_list(merge_two(None, from_list([0]))) == [0]
    lists = [from_list([1, 4, 5]), from_list([1, 3, 4]), from_list([2, 6])]
    assert to_list(merge_k_lists(lists)) == [1, 1, 2, 3, 4, 4, 5, 6]
    assert merge_k_lists([]) is None
    assert merge_k_lists([None, None]) is None
    assert to_list(merge_k_lists([from_list([-2]), None, from_list([-3, 9])])) == [-3, -2, 9]
    print("all tests passed")

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

Edge cases

Empty input list. All lists empty. A single list. Lists of very different lengths. Negative values. Equal values across lists (the tie-breaker index prevents comparing nodes).

Pattern

K-way merge with a heap. It is also used for external sorting of files too large for memory, merging sorted log files from many servers, and finding the smallest range covering k lists.

python
import heapq


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


def from_list(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


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


def merge_two(a, b):
    """Merge two sorted lists by relinking nodes. O(len(a) + len(b))."""
    dummy = tail = ListNode(0)
    while a and b:
        if a.val <= b.val:          # <= keeps the merge stable
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next


def merge_k_lists(lists):
    """Merge k sorted lists with a min-heap of the current heads. O(N log k)."""
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)              # i breaks ties so nodes are never compared
    dummy = tail = ListNode(0)
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


if __name__ == "__main__":
    assert to_list(merge_two(from_list([1, 2, 4]), from_list([1, 3, 4]))) == [1, 1, 2, 3, 4, 4]
    assert to_list(merge_two(None, from_list([0]))) == [0]
    lists = [from_list([1, 4, 5]), from_list([1, 3, 4]), from_list([2, 6])]
    assert to_list(merge_k_lists(lists)) == [1, 1, 2, 3, 4, 4, 5, 6]
    assert merge_k_lists([]) is None
    assert merge_k_lists([None, None]) is None
    assert to_list(merge_k_lists([from_list([-2]), None, from_list([-3, 9])])) == [-3, -2, 9]
    print("all tests passed")

heapq with (value, list index, node) tuples so nodes are never compared; merge_two is included for the divide-and-conquer version.

Complexity

Time: O(N log k). Space: O(k) for the heap. Sequential merging is O(N * k); divide and conquer matches the heap bound.

By level

Fresher: Gives the sort-everything approach, then explains the heap of heads and implements it. Should be able to merge two sorted lists with a dummy head.

Mid: Handles Python's comparison issue, analyses O(N log k) and presents divide and conquer. Adds a tie-breaker so nodes are never compared.

Senior: Applies k-way merge to external sorting and distributed log merging, and discusses memory, I/O and heap versus tournament tree trade-offs. Can compare heap and divide-and-conquer merging by memory use.

Key points

  • The next output node is the smallest current head
  • A heap of k heads gives O(log k) per step
  • Add a tie-breaker so nodes are not compared
  • Dummy head simplifies building the result
  • Divide and conquer is an equal alternative

Common mistakes

  • Pushing ListNode objects without a tie-breaker
  • Merging lists one by one and calling it optimal
  • Forgetting to push the successor
  • Dropping empty lists incorrectly or pushing None

Follow-ups

  • How would you merge k sorted files that do not fit in memory?
  • How do you find the smallest range that includes a number from each list?
  • When would divide and conquer beat the heap in practice?

Tips

  • Explain why the minimum is among the heads
  • Mention the tie-breaker issue in Python
  • State N and k separately in the complexity

Evaluation rubric

  • Correct heap-based merge
  • Correct complexity in N and k
  • Handles empty lists
  • Mentions an alternative
42.algorithms-0042Hardsenior

Design an LRU cache with O(1) get and put, evicting the least recently used key when the cache is full.

Combine a hash map from key to node with a doubly linked list ordered by recency. get moves the node to the front; put inserts at the front and, when full, removes the node at the back. Both operations are O(1) because the map finds the node and the doubly linked list removes it without a scan. In Python, OrderedDict with move_to_end gives the same behaviour.

Full answer

Problem

Implement LRUCache(capacity) with:

  • get(key): return the value, or -1 if absent; mark the key as most recently used.
  • put(key, value): insert or update; if this adds a key beyond capacity, evict the least recently used key first.

Both must be O(1) average time.

Example: capacity 2: put(1, 1), put(2, 2), get(1) returns 1, put(3, 3) evicts key 2, get(2) returns -1.

Constraints: capacity >= 1 (0 raises ValueError), up to 2 x 10^5 calls.

Brute force

Store (key, value) in a list ordered by use: lookups and moves are O(n). Storing a timestamp per key in a dict makes get O(1) but eviction needs a scan for the oldest, O(n).

Optimal approach

  • map: key to node.
  • Doubly linked list with two sentinel nodes, head and tail; head.next is the most recent, tail.prev the least recent.
  • get: look up the node; if found, unlink it and re-insert after head.
  • put: if the key exists, update its value and move it to the front. Otherwise, if full, unlink tail.prev and delete its key from the map; then add a new node at the front.

Each node stores its key so eviction can delete the map entry.

Why it works

The list order is always the recency order: every access moves the accessed node to the front, so the back node is the least recently used. The map gives direct access to any node, and a doubly linked list can unlink a known node in O(1) by joining its neighbours. Sentinels remove the special cases for empty lists and end nodes.

Complexity

O(1) average time for get and put. O(capacity) space.

Code

python
class Node:
    __slots__ = ("key", "value", "prev", "next")

    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None


class LRUCache:
    """get and put in O(1): hash map for lookup + doubly linked list for recency."""

    def __init__(self, capacity):
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self.map = {}
        self.head, self.tail = Node(), Node()      # sentinels: head.next is most recent
        self.head.next, self.tail.prev = self.tail, self.head

    def _remove(self, node):
        node.prev.next, node.next.prev = node.next, node.prev

    def _add_front(self, node):
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node

    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._remove(node)
        self._add_front(node)                      # now most recently used
        return node.value

    def put(self, key, value):
        node = self.map.get(key)
        if node:
            node.value = value
            self._remove(node)
            self._add_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev                   # least recently used
            self._remove(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._add_front(node)


if __name__ == "__main__":
    c = LRUCache(2)
    c.put(1, 1)
    c.put(2, 2)
    assert c.get(1) == 1          # order now: 1, 2
    c.put(3, 3)                   # evicts 2
    assert c.get(2) == -1
    c.put(4, 4)                   # evicts 1
    assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
    c.put(4, 40)                  # update keeps size
    assert c.get(4) == 40 and len(c.map) == 2
    one = LRUCache(1)
    one.put("a", 1)
    one.put("b", 2)
    assert one.get("a") == -1 and one.get("b") == 2
    try:
        LRUCache(0)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

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

Edge cases

Capacity 1 (every new key evicts the previous one). Updating an existing key must not evict anything and must refresh its recency. get on a missing key returns -1 without changing order. Capacity 0 is rejected. Thread safety: concurrent callers need a lock around each operation.

Pattern

Hash map plus doubly linked list: a composite structure where each part covers the other's weakness. Python's functools.lru_cache and collections.OrderedDict provide the same behaviour in production code. Related designs: LFU cache (frequency buckets) and time-based expiry.

python
class Node:
    __slots__ = ("key", "value", "prev", "next")

    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None


class LRUCache:
    """get and put in O(1): hash map for lookup + doubly linked list for recency."""

    def __init__(self, capacity):
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self.map = {}
        self.head, self.tail = Node(), Node()      # sentinels: head.next is most recent
        self.head.next, self.tail.prev = self.tail, self.head

    def _remove(self, node):
        node.prev.next, node.next.prev = node.next, node.prev

    def _add_front(self, node):
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node

    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._remove(node)
        self._add_front(node)                      # now most recently used
        return node.value

    def put(self, key, value):
        node = self.map.get(key)
        if node:
            node.value = value
            self._remove(node)
            self._add_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev                   # least recently used
            self._remove(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._add_front(node)


if __name__ == "__main__":
    c = LRUCache(2)
    c.put(1, 1)
    c.put(2, 2)
    assert c.get(1) == 1          # order now: 1, 2
    c.put(3, 3)                   # evicts 2
    assert c.get(2) == -1
    c.put(4, 4)                   # evicts 1
    assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
    c.put(4, 40)                  # update keeps size
    assert c.get(4) == 40 and len(c.map) == 2
    one = LRUCache(1)
    one.put("a", 1)
    one.put("b", 2)
    assert one.get("a") == -1 and one.get("b") == 2
    try:
        LRUCache(0)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Dict plus doubly linked list with head and tail sentinels; nodes store their key for eviction.

Complexity

Time: O(1) average for get and put. Space: O(capacity). OrderedDict.move_to_end and popitem(last=False) give the same O(1) behaviour.

By level

Fresher: Explains the hash map and linked list combination and walks through the example sequence. Should explain what least recently used means with an example.

Mid: Implements the design with sentinels, handles updates and capacity 1, and mentions OrderedDict. Tests capacity 1 and updates to an existing key.

Senior: Extends to LFU and TTL, discusses locking or sharded caches for concurrency and approximated LRU in systems such as Redis. Can explain why the node must store its key.

Key points

  • Hash map finds the node in O(1)
  • Doubly linked list keeps recency order and unlinks in O(1)
  • Move to front on every get and put
  • Evict the node before the tail sentinel
  • Store the key in the node to delete it from the map

Common mistakes

  • Using a singly linked list and scanning for the previous node
  • Forgetting to remove the evicted key from the map
  • Not refreshing recency on update
  • Evicting on update of an existing key

Follow-ups

  • How would you implement an LFU cache?
  • How do you add time-to-live expiry?
  • How would you make this safe for concurrent use?

Tips

  • Explain why each structure alone is not enough
  • Use sentinels to avoid special cases
  • Trace the eviction example

Evaluation rubric

  • Correct O(1) design
  • Correct recency updates
  • Correct eviction and map cleanup
  • Handles capacity edge cases
43.algorithms-0043Mediumfresher

Implement merge sort, explain why it is O(n log n) and why it is stable.

Split the list in half, sort each half recursively and merge the two sorted halves by repeatedly taking the smaller front element. There are log n levels of splitting and each level does O(n) merging work, so the total is O(n log n) in every case. Taking from the left half on ties keeps equal elements in their original order, which makes it stable. It needs O(n) extra space.

Full answer

Problem

Sort a list of comparable values and return a new sorted list, keeping the input unchanged.

Example: [38, 27, 43, 3, 9, 82, 10] gives [3, 9, 10, 27, 38, 43, 82].

Constraints: 0 <= n <= 10^5; values may repeat; the sort must be stable (equal values keep their input order).

Brute force

Selection or insertion sort: O(n^2) comparisons, about 5 x 10^9 for n = 10^5.

Optimal approach

  1. Base case: lists of length 0 or 1 are sorted.
  2. Split at mid = len(nums) // 2; sort both halves recursively.
  3. Merge: two indices i and j; append left[i] if left[i] <= right[j], otherwise right[j]; then append whatever remains.

Why it works

Correctness: the merge always takes the smallest remaining element, because each half is sorted and the smallest remaining element of a half is at its front.

Running time: the recursion tree has about log2(n) levels. On each level, the merges together touch every element once, so each level costs O(n). Total O(n log n), the same for best, average and worst cases.

Stability: on ties the merge takes from the left half, which holds elements that came earlier in the input, so equal elements never swap order. Using < instead of <= would break stability.

Complexity

O(n log n) time in all cases. O(n) extra space for the merged lists, plus O(log n) recursion depth.

Code

python
def merge_sort(nums):
    """Stable merge sort returning a new list. O(n log n) time, O(n) extra space."""
    if len(nums) <= 1:
        return list(nums)
    mid = len(nums) // 2
    left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])
    return merge(left, right)


def merge(left, right):
    out = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:      # <= takes from the left on ties: stable
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out


if __name__ == "__main__":
    assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
    assert merge_sort([]) == []
    assert merge_sort([1]) == [1]
    assert merge_sort([5, 5, 1, 5]) == [1, 5, 5, 5]
    assert merge_sort([3, -1, 0, -1]) == [-1, -1, 0, 3]
    data = [9, 1, 8, 2]
    assert merge_sort(data) == [1, 2, 8, 9] and data == [9, 1, 8, 2]   # input unchanged
    print("all tests passed")

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

Edge cases

Empty list and single element. All equal values. Negative numbers. The input list is not modified (the test checks this). Very large lists work because recursion depth is only about log2(n), around 17 for 10^5.

Pattern

Divide and conquer: split, solve halves, combine. The merge step is reused in counting inversions, merging k sorted lists and external sorting. Python's built-in sorted uses Timsort, a stable hybrid of merge sort and insertion sort.

python
def merge_sort(nums):
    """Stable merge sort returning a new list. O(n log n) time, O(n) extra space."""
    if len(nums) <= 1:
        return list(nums)
    mid = len(nums) // 2
    left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])
    return merge(left, right)


def merge(left, right):
    out = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:      # <= takes from the left on ties: stable
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out


if __name__ == "__main__":
    assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
    assert merge_sort([]) == []
    assert merge_sort([1]) == [1]
    assert merge_sort([5, 5, 1, 5]) == [1, 5, 5, 5]
    assert merge_sort([3, -1, 0, -1]) == [-1, -1, 0, 3]
    data = [9, 1, 8, 2]
    assert merge_sort(data) == [1, 2, 8, 9] and data == [9, 1, 8, 2]   # input unchanged
    print("all tests passed")

Recursive merge sort returning a new list; ties take from the left half to stay stable.

Complexity

Time: O(n log n) in all cases. Space: O(n) extra plus O(log n) recursion. Python's built-in sorted uses Timsort, a stable merge-based hybrid.

By level

Fresher: Implements merge sort with the merge helper and explains the levels-times-work argument. Should test an empty list and equal values.

Mid: Explains stability with ties, compares with quicksort and mentions inversion counting. Explains why < in the merge breaks stability.

Senior: Discusses Timsort, external merge sort for disk data, bottom-up iterative merge sort and parallel merging. Explains why Python uses Timsort.

Key points

  • Split, sort halves, merge
  • log n levels with O(n) work each
  • Same time in best, average and worst cases
  • <= in the merge keeps it stable
  • O(n) extra space

Common mistakes

  • Using < in the merge and losing stability
  • Forgetting to append the leftover elements
  • Slicing in a way that loses or repeats an element
  • Claiming it sorts in place with O(1) space

Follow-ups

  • How would you count inversions using merge sort?
  • How would you sort a linked list in O(n log n)?
  • Why does Python use Timsort?

Tips

  • Draw the recursion tree to explain log n levels
  • Show a tie to explain stability
  • Mention space cost

Evaluation rubric

  • Correct implementation
  • Correct complexity argument
  • Explains stability correctly
  • Handles edge cases
44.algorithms-0044Mediummid

Implement quicksort in place, explain its average and worst cases, and show how pivot choice and duplicates affect it.

Pick a pivot, partition the list so smaller values come before it and the rest after it, then sort both sides. With balanced splits the depth is log n, giving O(n log n) average time; a bad pivot on every step gives O(n^2). A random pivot makes the worst case very unlikely, recursing on the smaller side caps the stack at O(log n), and three-way partitioning fixes slow behaviour on many duplicates. It is not stable.

Full answer

Problem

Sort a list of numbers in place using quicksort.

Example: [10, 7, 8, 9, 1, 5] becomes [1, 5, 7, 8, 9, 10].

Constraints: 0 <= n <= 10^5; values may repeat; input may already be sorted.

Brute force

Insertion sort: O(n^2) on average. Quicksort with the last element as pivot is also O(n^2) on already sorted input, because each partition removes only one element.

Optimal approach

Lomuto partition on nums[lo..hi]:

  1. Choose a random index as pivot and swap it to hi.
  2. i = lo; for each j in lo..hi - 1, if nums[j] < pivot, swap it into position i and increment i.
  3. Swap the pivot into i; it is now in its final place.

Sorting loop: after partitioning, recurse on the smaller side and loop on the larger side. That keeps the recursion depth at O(log n) even in a bad case.

Three-way version (quick_sort_3way in the code): split into less than, equal to and greater than the pivot. The equal group is never processed again, so a list of many equal keys sorts in near-linear time.

Why it works

After partitioning, every element left of the pivot is smaller, every element right of it is at least as large, and the pivot is in its sorted position. Sorting each side independently therefore sorts the whole list, by induction on size.

Average O(n log n): a random pivot lands in the middle half of the values with probability 1/2, so on average the sizes shrink geometrically and the expected depth is O(log n), with O(n) partition work per level. Worst case O(n^2) happens when every pivot is the minimum or maximum.

Duplicates: with two-way Lomuto, a list of all equal values puts everything on one side every time, which is O(n^2). Three-way partitioning avoids that.

Complexity

Average O(n log n), worst O(n^2) time. O(log n) stack with smaller-side recursion. The three-way version in the code builds new lists, so it uses O(n) extra space; the in-place Dutch national flag partition avoids that.

Code

python
import random


def quick_sort(nums, rng=None):
    """In-place quicksort with random pivot and Lomuto partition. Average O(n log n)."""
    rng = rng or random.Random(42)        # fixed seed so runs are repeatable

    def partition(lo, hi):
        p = rng.randint(lo, hi)           # random pivot avoids sorted-input worst case
        nums[p], nums[hi] = nums[hi], nums[p]
        pivot = nums[hi]
        i = lo
        for j in range(lo, hi):
            if nums[j] < pivot:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
        nums[i], nums[hi] = nums[hi], nums[i]
        return i                          # pivot is now in its final position

    def sort(lo, hi):
        while lo < hi:
            p = partition(lo, hi)
            if p - lo < hi - p:           # recurse on the smaller side: O(log n) stack
                sort(lo, p - 1)
                lo = p + 1
            else:
                sort(p + 1, hi)
                hi = p - 1

    sort(0, len(nums) - 1)
    return nums


def quick_sort_3way(nums):
    """Simple, not in place: splits into <, ==, > the pivot. Handles many duplicates well."""
    if len(nums) <= 1:
        return list(nums)
    pivot = nums[len(nums) // 2]
    return (quick_sort_3way([x for x in nums if x < pivot])
            + [x for x in nums if x == pivot]
            + quick_sort_3way([x for x in nums if x > pivot]))


if __name__ == "__main__":
    for f in (quick_sort, quick_sort_3way):
        assert f([10, 7, 8, 9, 1, 5]) == [1, 5, 7, 8, 9, 10]
        assert f([]) == []
        assert f([2]) == [2]
        assert f([3, 3, 3, 1]) == [1, 3, 3, 3]
        assert f(list(range(2000))) == list(range(2000))          # sorted input
        assert f(list(range(2000, 0, -1))) == list(range(1, 2001))
    print("all tests passed")

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

Edge cases

Empty and single-element lists. Already sorted and reverse sorted input of 2000 elements (the random pivot keeps these fast). Many duplicates (use three-way partitioning). The random generator uses a fixed seed, so runs are repeatable.

Quicksort is not stable: partition swaps can move equal elements past each other. Use merge sort or Python's sorted when stability matters.

Pattern

Partition-based divide and conquer. The same partition step powers quickselect (k-th smallest in average O(n)), Dutch national flag (sort colours) and moving all zeros to the end.

python
import random


def quick_sort(nums, rng=None):
    """In-place quicksort with random pivot and Lomuto partition. Average O(n log n)."""
    rng = rng or random.Random(42)        # fixed seed so runs are repeatable

    def partition(lo, hi):
        p = rng.randint(lo, hi)           # random pivot avoids sorted-input worst case
        nums[p], nums[hi] = nums[hi], nums[p]
        pivot = nums[hi]
        i = lo
        for j in range(lo, hi):
            if nums[j] < pivot:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
        nums[i], nums[hi] = nums[hi], nums[i]
        return i                          # pivot is now in its final position

    def sort(lo, hi):
        while lo < hi:
            p = partition(lo, hi)
            if p - lo < hi - p:           # recurse on the smaller side: O(log n) stack
                sort(lo, p - 1)
                lo = p + 1
            else:
                sort(p + 1, hi)
                hi = p - 1

    sort(0, len(nums) - 1)
    return nums


def quick_sort_3way(nums):
    """Simple, not in place: splits into <, ==, > the pivot. Handles many duplicates well."""
    if len(nums) <= 1:
        return list(nums)
    pivot = nums[len(nums) // 2]
    return (quick_sort_3way([x for x in nums if x < pivot])
            + [x for x in nums if x == pivot]
            + quick_sort_3way([x for x in nums if x > pivot]))


if __name__ == "__main__":
    for f in (quick_sort, quick_sort_3way):
        assert f([10, 7, 8, 9, 1, 5]) == [1, 5, 7, 8, 9, 10]
        assert f([]) == []
        assert f([2]) == [2]
        assert f([3, 3, 3, 1]) == [1, 3, 3, 3]
        assert f(list(range(2000))) == list(range(2000))          # sorted input
        assert f(list(range(2000, 0, -1))) == list(range(1, 2001))
    print("all tests passed")

In-place Lomuto quicksort with a seeded random pivot (random.Random(42)) and smaller-side recursion, plus a simple three-way version.

Complexity

Time: Average O(n log n); worst O(n^2). Space: O(log n) stack for the in-place version; O(n) for the list-building three-way version. Introsort, used by many C++ libraries, switches to heapsort when recursion gets too deep, guaranteeing O(n log n).

By level

Fresher: Implements partition and recursion, and explains why a sorted input with a last-element pivot is slow. Should state that quicksort is not stable.

Mid: Uses random pivots, smaller-side recursion and three-way partitioning, and explains average-case reasoning. Tests sorted, reverse sorted and all-equal inputs.

Senior: Compares quicksort, merge sort and introsort in cache behaviour and guarantees, and discusses pivot strategies such as median of three. Explains why introsort exists.

Key points

  • Partition puts the pivot in its final place
  • Average O(n log n), worst O(n^2)
  • Random pivot avoids sorted-input worst case
  • Recurse on the smaller side for O(log n) stack
  • Three-way partition handles duplicates; not stable

Common mistakes

  • Always choosing the first or last element as pivot
  • Claiming quicksort is stable
  • Recursing on both sides and overflowing the stack on bad input
  • Ignoring the all-equal-values worst case

Follow-ups

  • How does quickselect find the k-th smallest element?
  • Why do some libraries use introsort?
  • When would you prefer merge sort over quicksort?

Tips

  • State average and worst case separately
  • Explain the random pivot with a sorted-input example
  • Mention stability

Evaluation rubric

  • Correct partition and recursion
  • Correct complexity discussion
  • Addresses pivot choice and duplicates
  • Notes instability
45.algorithms-0045Mediummid

Counting sort and stability: sort records by a small integer key in O(n + k), keep equal keys in input order, and use it to build radix sort.

Count how many records have each key, turn the counts into starting positions with a prefix sum, then place each record at its key's next free position, scanning left to right. That is O(n + k) and stable. Comparison sorts cannot beat O(n log n), but counting sort avoids comparisons when keys are small integers. Radix sort applies stable counting sort digit by digit, and stability is what makes it correct.

Full answer

Problem

Sort a list of records by an integer key in [0, max_key], stably. Then use it to sort non-negative integers digit by digit (LSD radix sort).

Example: students [("Asha", 3), ("Ben", 1), ("Chen", 3), ("Dara", 2), ("Eli", 1)] sorted by grade gives [("Ben", 1), ("Eli", 1), ("Dara", 2), ("Asha", 3), ("Chen", 3)]: Ben stays before Eli and Asha before Chen.

Constraints: n <= 10^6, max_key <= 10^6.

Brute force

Any comparison sort, O(n log n). Python's sorted(records, key=...) is stable and is the right tool in everyday code; counting sort matters when n is large and keys are small.

Optimal approach

  1. counts[v] = number of records with key v.
  2. starts[v] = sum of counts for all smaller keys (a prefix sum): the first output index for key v.
  3. For each record in input order, write it to out[starts[key]] and increment starts[key].

Radix sort for non-negative integers: for exp = 1, 10, 100, ... while some number still has a digit at that place, counting-sort by (x // exp) % 10.

Why it works

The prefix sums reserve a block of output positions for each key, in key order. Scanning the input left to right fills each block in input order, so equal keys keep their relative order: the sort is stable.

Radix sort: after processing digit d, the numbers are sorted by their last d digits. Sorting by the next digit stably keeps that order among numbers whose next digit is equal, so by induction the final pass sorts by all digits. An unstable digit sort would scramble the lower digits.

Complexity

Counting sort: O(n + k) time and space, where k = max_key + 1. Radix sort: O(d x (n + 10)) for d digits. Counting sort becomes poor when k is much larger than n (for example, keys up to 10^9).

Code

python
def counting_sort(records, key, max_key):
    """Stable counting sort of records by an integer key in [0, max_key]. O(n + k)."""
    counts = [0] * (max_key + 1)
    for r in records:
        counts[key(r)] += 1
    starts = [0] * (max_key + 1)          # starts[v] = first output index for key v
    for v in range(1, max_key + 1):
        starts[v] = starts[v - 1] + counts[v - 1]
    out = [None] * len(records)
    for r in records:                     # left to right keeps equal keys in input order
        out[starts[key(r)]] = r
        starts[key(r)] += 1
    return out


def radix_sort(nums):
    """LSD radix sort for non-negative integers, using stable counting sort per digit."""
    if not nums:
        return []
    exp = 1
    while max(nums) // exp > 0:
        nums = counting_sort(nums, key=lambda x: (x // exp) % 10, max_key=9)
        exp *= 10
    return nums


if __name__ == "__main__":
    students = [("Asha", 3), ("Ben", 1), ("Chen", 3), ("Dara", 2), ("Eli", 1)]
    by_grade = counting_sort(students, key=lambda s: s[1], max_key=3)
    assert by_grade == [("Ben", 1), ("Eli", 1), ("Dara", 2), ("Asha", 3), ("Chen", 3)]
    assert counting_sort([], key=lambda x: x, max_key=5) == []
    assert counting_sort([4, 0, 4, 2], key=lambda x: x, max_key=4) == [0, 2, 4, 4]
    assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
    assert radix_sort([0, 0]) == [0, 0]
    assert radix_sort([]) == []
    print("all tests passed")

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

Edge cases

Empty input. All keys equal. Keys at both ends of the range. Negative keys need an offset (subtract the minimum). Radix sort with zeros only ([0, 0]). Large ranges with few records: use a comparison sort or radix sort with a larger base instead.

Pattern

Non-comparison sorting with counts and prefix sums. Stability as a building block for multi-key sorting: sort by the secondary key, then stably by the primary key. Bucket sort follows the same idea for evenly distributed real values.

python
def counting_sort(records, key, max_key):
    """Stable counting sort of records by an integer key in [0, max_key]. O(n + k)."""
    counts = [0] * (max_key + 1)
    for r in records:
        counts[key(r)] += 1
    starts = [0] * (max_key + 1)          # starts[v] = first output index for key v
    for v in range(1, max_key + 1):
        starts[v] = starts[v - 1] + counts[v - 1]
    out = [None] * len(records)
    for r in records:                     # left to right keeps equal keys in input order
        out[starts[key(r)]] = r
        starts[key(r)] += 1
    return out


def radix_sort(nums):
    """LSD radix sort for non-negative integers, using stable counting sort per digit."""
    if not nums:
        return []
    exp = 1
    while max(nums) // exp > 0:
        nums = counting_sort(nums, key=lambda x: (x // exp) % 10, max_key=9)
        exp *= 10
    return nums


if __name__ == "__main__":
    students = [("Asha", 3), ("Ben", 1), ("Chen", 3), ("Dara", 2), ("Eli", 1)]
    by_grade = counting_sort(students, key=lambda s: s[1], max_key=3)
    assert by_grade == [("Ben", 1), ("Eli", 1), ("Dara", 2), ("Asha", 3), ("Chen", 3)]
    assert counting_sort([], key=lambda x: x, max_key=5) == []
    assert counting_sort([4, 0, 4, 2], key=lambda x: x, max_key=4) == [0, 2, 4, 4]
    assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
    assert radix_sort([0, 0]) == [0, 0]
    assert radix_sort([]) == []
    print("all tests passed")

Stable counting sort with a key function and prefix-sum start positions; LSD radix sort calls it once per decimal digit.

Complexity

Time: O(n + k) for counting sort; O(d * (n + 10)) for radix sort. Space: O(n + k). The Omega(n log n) lower bound applies only to comparison sorts.

By level

Fresher: Explains counting with an array of counts and shows stability on the student list. Should state when counting sort is a poor choice.

Mid: Implements the prefix-sum version, builds radix sort and explains why stability is required. Handles negative keys with an offset.

Senior: Discusses the comparison lower bound, memory and cache effects for large k, radix base choice and multi-key sorting. Can explain why the comparison lower bound does not apply here.

Key points

  • Count, prefix-sum into start positions, place left to right
  • Left-to-right placement makes it stable
  • O(n + k), good when keys are small
  • Radix sort needs a stable per-digit sort
  • Comparison sorts are bounded by n log n; counting sort is not a comparison sort

Common mistakes

  • Rebuilding output from counts and losing the records attached to keys
  • Placing right to left with forward start positions and breaking stability
  • Using counting sort with a huge key range
  • Forgetting an offset for negative keys

Follow-ups

  • How would you sort by two keys using stable sorts?
  • How would you handle negative integers in radix sort?
  • When is bucket sort a good choice?

Tips

  • Define stability with the student example
  • Explain the prefix-sum step
  • State the conditions where counting sort wins

Evaluation rubric

  • Correct stable counting sort
  • Correct radix sort reasoning
  • Correct complexity in n and k
  • Explains when not to use it
46.algorithms-0046Mediummid

Find the k-th largest element in an unsorted list without fully sorting it, using a heap and using quickselect.

A min-heap of size k keeps the k largest values seen; its top is the k-th largest. That costs O(n log k) time and O(k) space and works on streams. Quickselect partitions like quicksort but recurses only into the side containing the target index, giving O(n) average time with a random pivot, O(n^2) in the worst case.

Full answer

Problem

Given nums and k, return the k-th largest value (counting duplicates; for [3, 2, 3, 1, 2, 4, 5, 5, 6] and k = 4 the answer is 4).

Example: [3, 2, 1, 5, 6, 4], k = 2 gives 5.

Constraints: 1 <= k <= len(nums) <= 10^5. The quickselect version raises ValueError for an invalid k.

Brute force

Sort descending and take index k - 1: O(n log n). Simple and often fine; interviewers then ask for something faster.

Optimal approach

Heap:

  1. Push each value onto a min-heap.
  2. If the heap holds more than k values, pop the smallest.
  3. At the end the heap holds the k largest; heap[0] is the k-th largest.

Quickselect:

  1. Target index in ascending order: len(nums) - k.
  2. Partition around a random pivot (Lomuto); the pivot lands at index i.
  3. If i == target, return it; if i < target, continue on the right part; otherwise the left part.

Why it works

Heap: the invariant is "the heap contains the k largest values seen so far". A new value either enters, pushing out the smallest of the k + 1, or is too small. The smallest of the k largest is the k-th largest.

Quickselect: after partitioning, the pivot is in its final sorted position. The target is on exactly one side, so the other side can be ignored. With a random pivot the part shrinks by a constant factor on average, so the total work is about n + n/2 + n/4 + ... = O(n).

Complexity

Heap: O(n log k) time, O(k) space. Quickselect: O(n) average, O(n^2) worst, O(n) space here because it copies the input to avoid changing it (O(1) extra if done in place). Median of medians guarantees O(n) worst case but is slower in practice.

Code

python
import heapq
import random


def kth_largest_heap(nums, k):
    """Keep a min-heap of the k largest values seen. O(n log k) time, O(k) space."""
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)          # drop the smallest of the k + 1
    return heap[0]


def kth_largest_quickselect(nums, k, seed=7):
    """Average O(n), worst O(n^2) (made unlikely by a random pivot). Copies the input."""
    if not 1 <= k <= len(nums):
        raise ValueError("need 1 <= k <= len(nums)")
    rng = random.Random(seed)
    a = list(nums)
    target = len(a) - k                  # index of the answer in ascending order
    lo, hi = 0, len(a) - 1
    while True:
        p = rng.randint(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        if i == target:
            return a[i]
        if i < target:
            lo = i + 1
        else:
            hi = i - 1


if __name__ == "__main__":
    for f in (kth_largest_heap, kth_largest_quickselect):
        assert f([3, 2, 1, 5, 6, 4], 2) == 5
        assert f([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
        assert f([1], 1) == 1
        assert f([2, 2, 2], 2) == 2
        assert f([-1, -5, 0], 3) == -5
    try:
        kth_largest_quickselect([1, 2], 3)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

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

Edge cases

k = 1 (maximum) and k = n (minimum). Duplicates count separately. Negative values. All values equal. Invalid k is rejected by the quickselect version. heapq.nlargest(k, nums)[-1] is a one-line library option.

Pattern

Top-k selection with a bounded heap, and partition-based selection. Related: top k frequent elements, k closest points to the origin, and a running median with two heaps.

python
import heapq
import random


def kth_largest_heap(nums, k):
    """Keep a min-heap of the k largest values seen. O(n log k) time, O(k) space."""
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)          # drop the smallest of the k + 1
    return heap[0]


def kth_largest_quickselect(nums, k, seed=7):
    """Average O(n), worst O(n^2) (made unlikely by a random pivot). Copies the input."""
    if not 1 <= k <= len(nums):
        raise ValueError("need 1 <= k <= len(nums)")
    rng = random.Random(seed)
    a = list(nums)
    target = len(a) - k                  # index of the answer in ascending order
    lo, hi = 0, len(a) - 1
    while True:
        p = rng.randint(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        if i == target:
            return a[i]
        if i < target:
            lo = i + 1
        else:
            hi = i - 1


if __name__ == "__main__":
    for f in (kth_largest_heap, kth_largest_quickselect):
        assert f([3, 2, 1, 5, 6, 4], 2) == 5
        assert f([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
        assert f([1], 1) == 1
        assert f([2, 2, 2], 2) == 2
        assert f([-1, -5, 0], 3) == -5
    try:
        kth_largest_quickselect([1, 2], 3)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Bounded min-heap version and seeded quickselect (random.Random(7)) that copies the input; both pass the same tests.

Complexity

Time: Heap O(n log k); quickselect O(n) average, O(n^2) worst. Space: Heap O(k); quickselect O(n) for the copy. Median of medians gives a worst-case O(n) selection.

By level

Fresher: Implements the size-k min-heap and explains why its top is the answer. Should give the sort-based baseline first.

Mid: Adds quickselect with a random pivot and compares the two on time, space and streaming use. States the target index formula for quickselect.

Senior: Discusses worst-case guarantees with median of medians, distributed top-k and approximate methods for very large data. Can explain why the heap version suits streams better than quickselect.

Key points

  • Min-heap of size k keeps the k largest
  • Heap top is the answer
  • Quickselect only follows the side with the target
  • Target index is n - k in ascending order
  • Heap works on streams; quickselect needs all data

Common mistakes

  • Using a max-heap of all n values and calling it O(n log k)
  • Off-by-one between k-th largest and index
  • Forgetting that quickselect has an O(n^2) worst case
  • Removing duplicates when they should count

Follow-ups

  • How would you find the k-th largest in a stream?
  • How do you get the k closest points to a location?
  • What is median of medians?

Tips

  • Give the sort solution and its cost first
  • Compare heap and quickselect trade-offs
  • State the target index formula

Evaluation rubric

  • Correct heap or quickselect implementation
  • Correct complexity for both
  • Handles duplicates and k bounds
  • Discusses trade-offs
47.algorithms-0047Mediummid

Implement a binary min-heap with push, pop and peek, and build a heap from a list in O(n).

Store a complete binary tree in a list: the children of index i are 2i + 1 and 2i + 2, and the parent is (i - 1) // 2. push appends and sifts up; pop moves the last element to the root and sifts down; both are O(log n). Building a heap by sifting down from the last parent to the root is O(n), because most nodes are near the bottom and move only a little.

Full answer

Problem

Implement MinHeap with push(x), pop() (remove and return the smallest), peek(), len() and a constructor that builds a heap from a list.

Example: push 5, 3, 8, 1, 9, 2; popping six times returns 1, 2, 3, 5, 8, 9.

Constraints: up to 10^5 operations; pop and peek on an empty heap raise IndexError.

Brute force

A sorted list: peek and pop from the front are cheap if you keep it reversed, but each insert is O(n) because elements must shift. An unsorted list makes insert O(1) and pop O(n).

Optimal approach

Heap property: every parent is at most its children, so the minimum is at index 0.

  • push: append, then sift up: swap with the parent while smaller than it.
  • pop: save the root, move the last element to the root, then sift down: swap with the smaller child while larger than it.
  • Build: for i from n // 2 - 1 down to 0, sift down. Leaves already satisfy the property.

Why it works

A complete binary tree with n nodes has height about log2(n). Sift up and sift down each move one level per swap and fix the only place where the heap property can be broken, so push and pop are O(log n).

Bottom-up build is O(n): about n/2 nodes are leaves and never move, n/4 move at most one level, n/8 at most two, and so on. The sum n/4 x 1 + n/8 x 2 + n/16 x 3 + ... is less than n.

Complexity

push and pop: O(log n). peek: O(1). Build from a list: O(n). Space O(n).

Code

python
class MinHeap:
    """Binary min-heap in a list. push/pop O(log n), peek O(1), heapify O(n)."""

    def __init__(self, items=None):
        self.a = list(items or [])
        for i in range(len(self.a) // 2 - 1, -1, -1):   # bottom-up heapify
            self._sift_down(i)

    def push(self, x):
        self.a.append(x)
        self._sift_up(len(self.a) - 1)

    def pop(self):
        if not self.a:
            raise IndexError("pop from empty heap")
        top = self.a[0]
        last = self.a.pop()
        if self.a:
            self.a[0] = last
            self._sift_down(0)
        return top

    def peek(self):
        if not self.a:
            raise IndexError("peek from empty heap")
        return self.a[0]

    def _sift_up(self, i):
        while i > 0:
            parent = (i - 1) // 2
            if self.a[i] >= self.a[parent]:
                break
            self.a[i], self.a[parent] = self.a[parent], self.a[i]
            i = parent

    def _sift_down(self, i):
        n = len(self.a)
        while True:
            smallest, left, right = i, 2 * i + 1, 2 * i + 2
            if left < n and self.a[left] < self.a[smallest]:
                smallest = left
            if right < n and self.a[right] < self.a[smallest]:
                smallest = right
            if smallest == i:
                return
            self.a[i], self.a[smallest] = self.a[smallest], self.a[i]
            i = smallest

    def __len__(self):
        return len(self.a)


if __name__ == "__main__":
    h = MinHeap()
    for x in (5, 3, 8, 1, 9, 2):
        h.push(x)
    assert h.peek() == 1 and len(h) == 6
    assert [h.pop() for _ in range(6)] == [1, 2, 3, 5, 8, 9]
    for op in (h.pop, h.peek):
        try:
            op()
            raise AssertionError("expected IndexError")
        except IndexError:
            pass
    h2 = MinHeap([7, 7, 2, 4, 0, 4])
    assert [h2.pop() for _ in range(len(h2))] == [0, 2, 4, 4, 7, 7]
    print("all tests passed")

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

Edge cases

Pop or peek on an empty heap raise IndexError. Popping the last element (do not copy it back to the root). Duplicates ([7, 7, 2, 4, 0, 4]). In Python, the heapq module provides these operations on plain lists; for a max-heap, push negated values or (-priority, item) tuples.

Pattern

Priority queue. Heaps power Dijkstra's shortest paths, task schedulers, k-way merge, top-k selection, running medians and event simulation.

python
class MinHeap:
    """Binary min-heap in a list. push/pop O(log n), peek O(1), heapify O(n)."""

    def __init__(self, items=None):
        self.a = list(items or [])
        for i in range(len(self.a) // 2 - 1, -1, -1):   # bottom-up heapify
            self._sift_down(i)

    def push(self, x):
        self.a.append(x)
        self._sift_up(len(self.a) - 1)

    def pop(self):
        if not self.a:
            raise IndexError("pop from empty heap")
        top = self.a[0]
        last = self.a.pop()
        if self.a:
            self.a[0] = last
            self._sift_down(0)
        return top

    def peek(self):
        if not self.a:
            raise IndexError("peek from empty heap")
        return self.a[0]

    def _sift_up(self, i):
        while i > 0:
            parent = (i - 1) // 2
            if self.a[i] >= self.a[parent]:
                break
            self.a[i], self.a[parent] = self.a[parent], self.a[i]
            i = parent

    def _sift_down(self, i):
        n = len(self.a)
        while True:
            smallest, left, right = i, 2 * i + 1, 2 * i + 2
            if left < n and self.a[left] < self.a[smallest]:
                smallest = left
            if right < n and self.a[right] < self.a[smallest]:
                smallest = right
            if smallest == i:
                return
            self.a[i], self.a[smallest] = self.a[smallest], self.a[i]
            i = smallest

    def __len__(self):
        return len(self.a)


if __name__ == "__main__":
    h = MinHeap()
    for x in (5, 3, 8, 1, 9, 2):
        h.push(x)
    assert h.peek() == 1 and len(h) == 6
    assert [h.pop() for _ in range(6)] == [1, 2, 3, 5, 8, 9]
    for op in (h.pop, h.peek):
        try:
            op()
            raise AssertionError("expected IndexError")
        except IndexError:
            pass
    h2 = MinHeap([7, 7, 2, 4, 0, 4])
    assert [h2.pop() for _ in range(len(h2))] == [0, 2, 4, 4, 7, 7]
    print("all tests passed")

List-based binary min-heap with sift up, sift down and bottom-up heapify; the test checks sorted pop order.

Complexity

Time: push and pop O(log n); peek O(1); build O(n). Space: O(n). Bottom-up heapify is O(n) because most nodes are near the leaves.

By level

Fresher: Implements push and pop with sift up and sift down, and explains the index formulas. Should be able to draw the list as a tree.

Mid: Builds the heap bottom-up, explains why it is O(n) and uses heapq idioms for max-heaps. Tests popping until the heap is empty.

Senior: Discusses decrease-key with a position map, d-ary heaps and cache effects, and when a balanced tree or indexed heap fits better. Can compare a binary heap with a balanced search tree for priority queues.

Key points

  • Children of i are 2i + 1 and 2i + 2
  • Parent of i is (i - 1) // 2
  • Push sifts up; pop sifts down
  • Bottom-up build is O(n), not O(n log n)
  • heapq is a min-heap; negate values for a max-heap

Common mistakes

  • Swapping with the larger child during sift down
  • Copying the last element back after popping the only element
  • Claiming heapify is O(n log n) without nuance
  • Using a heap when a sorted order of everything is needed

Follow-ups

  • How do you implement decrease-key?
  • How would you build a max-heap with heapq?
  • How does heapsort work and is it stable?

Tips

  • Draw the list as a tree
  • State the index formulas
  • Explain the O(n) build informally

Evaluation rubric

  • Correct sift operations
  • Correct index arithmetic
  • Correct complexity including build
  • Handles empty heap
48.algorithms-0048Mediumfresher

Generate all subsets of a list using backtracking, and then handle a list that contains duplicate values.

Each element is either in or out, so there are 2^n subsets. Backtracking builds a current subset: record it, then for each later index choose that element, recurse, and undo the choice. For duplicates, sort first and skip a value equal to the previous one at the same depth, which removes repeated subsets without a set of results.

Full answer

Problem

Given a list nums, return every subset (the power set) in any order.

Example: [1, 2, 3] gives [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3].

Follow-up: with duplicates, [1, 2, 2] should give 6 distinct subsets, not 8: [], [1], [1, 2], [1, 2, 2], [2], [2, 2].

Constraints: 0 <= len(nums) <= 10.

Brute force

Bitmasks: for each mask from 0 to 2^n - 1, include nums[i] when bit i is set. Also O(n x 2^n). For duplicates, generating everything and deduplicating with a set of sorted tuples works but wastes effort.

Optimal approach

backtrack(start):

  1. Append a copy of current to the result (every partial choice is a subset).
  2. For i from start to the end: append nums[i], call backtrack(i + 1), pop it.

Duplicates: sort nums, and inside the loop skip i when i > start and nums[i] == nums[i - 1].

Why it works

Starting each loop at start means elements are always chosen in index order, so each subset is produced exactly once, as the path to one node of the recursion tree. Undoing the choice (pop) restores current for the next sibling.

Duplicate skipping: at a given depth, choosing the first or the second of two equal values leads to identical subsets. Sorting puts equal values together, and skipping later equal siblings keeps only the first branch. The condition i > start still allows taking both copies along one path ([2, 2]).

Complexity

O(n x 2^n) time: 2^n subsets, each copied in up to O(n). O(n) recursion depth, plus the output itself.

Code

python
def subsets(nums):
    """All subsets of distinct values via backtracking: include or skip each item."""
    result, current = [], []

    def backtrack(start):
        result.append(list(current))          # every partial choice is a subset
        for i in range(start, len(nums)):
            current.append(nums[i])           # choose
            backtrack(i + 1)                  # explore
            current.pop()                     # un-choose

    backtrack(0)
    return result


def subsets_with_dup(nums):
    """Subsets when nums may contain duplicates: sort, then skip equal siblings."""
    nums = sorted(nums)
    result, current = [], []

    def backtrack(start):
        result.append(list(current))
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            current.append(nums[i])
            backtrack(i + 1)
            current.pop()

    backtrack(0)
    return result


if __name__ == "__main__":
    assert sorted(subsets([1, 2, 3])) == sorted(
        [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]])
    assert subsets([]) == [[]]
    assert len(subsets(list(range(10)))) == 2 ** 10
    assert sorted(subsets_with_dup([1, 2, 2])) == sorted(
        [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]])
    assert subsets_with_dup([0]) == [[], [0]]
    print("all tests passed")

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

Edge cases

Empty input returns [[]]. Appending current without copying stores the same list object many times, which ends up empty. With duplicates, skipping with i > 0 instead of i > start wrongly removes [2, 2].

Pattern

Backtracking template: choose, explore, un-choose. The same template generates combinations of size k, permutations, combination sum and palindrome partitions.

python
def subsets(nums):
    """All subsets of distinct values via backtracking: include or skip each item."""
    result, current = [], []

    def backtrack(start):
        result.append(list(current))          # every partial choice is a subset
        for i in range(start, len(nums)):
            current.append(nums[i])           # choose
            backtrack(i + 1)                  # explore
            current.pop()                     # un-choose

    backtrack(0)
    return result


def subsets_with_dup(nums):
    """Subsets when nums may contain duplicates: sort, then skip equal siblings."""
    nums = sorted(nums)
    result, current = [], []

    def backtrack(start):
        result.append(list(current))
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            current.append(nums[i])
            backtrack(i + 1)
            current.pop()

    backtrack(0)
    return result


if __name__ == "__main__":
    assert sorted(subsets([1, 2, 3])) == sorted(
        [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]])
    assert subsets([]) == [[]]
    assert len(subsets(list(range(10)))) == 2 ** 10
    assert sorted(subsets_with_dup([1, 2, 2])) == sorted(
        [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]])
    assert subsets_with_dup([0]) == [[], [0]]
    print("all tests passed")

Backtracking with choose, explore and un-choose; the duplicate version sorts and skips equal siblings.

Complexity

Time: O(n * 2^n). Space: O(n) recursion depth, plus O(n * 2^n) output. Bitmask enumeration has the same bound.

By level

Fresher: Writes the include-or-skip recursion and lists the subsets for a short example. Should state that there are 2^n subsets.

Mid: Uses the loop-from-start template, handles duplicates with sorting and skipping, and explains the recursion tree. Tests a list with three equal values.

Senior: Compares backtracking with bitmasks and iterative generation, discusses output-sensitive complexity and pruning strategies. Can explain why the output size dominates the running time.

Key points

  • 2^n subsets
  • Record current at every node of the recursion tree
  • Choose, explore, un-choose
  • Loop from start so each subset appears once
  • Sort and skip equal siblings for duplicates

Common mistakes

  • Appending current without copying
  • Skipping duplicates with i > 0 instead of i > start
  • Deduplicating with a set instead of pruning
  • Forgetting to pop after the recursive call

Follow-ups

  • How would you generate only subsets of size k?
  • How do you generate all permutations?
  • How would you solve combination sum?

Tips

  • State 2^n before coding
  • Draw the recursion tree for three elements
  • Test [1, 2, 2]

Evaluation rubric

  • Correct backtracking
  • Correct duplicate handling
  • Correct complexity
  • Copies the current subset
49.algorithms-0049Hardsenior

N-Queens: place n queens on an n x n board so that no two attack each other, and return every valid board.

Place one queen per row. For each column in the current row, skip it if the column, the diagonal (r - c) or the anti-diagonal (r + c) is already used; otherwise place the queen, recurse to the next row and remove it afterwards. Sets make each conflict check O(1). The search is exponential but pruning keeps it fast for small n.

Full answer

Problem

Return all distinct placements of n queens on an n x n board with no two queens sharing a row, column or diagonal. Each board is a list of strings, with "Q" for a queen and "." for an empty square.

Example: n = 4 has 2 solutions: [".Q..", "...Q", "Q...", "..Q."] and ["..Q.", "Q...", "...Q", ".Q.."].

Constraints: 1 <= n <= 9. Solution counts for n = 1 to 8 are 1, 0, 0, 2, 10, 4, 40, 92.

Brute force

Try every choice of n squares out of n^2: C(64, 8), about 4.4 x 10^9 for n = 8. One queen per row reduces it to n^n (about 1.7 x 10^7), and one per column to n! (40320), still checking every full board.

Optimal approach

place(r):

  1. If r == n, record the board.
  2. For each column c: skip if c is in cols, r - c in diag or r + c in anti.
  3. Otherwise add c, r - c, r + c to the sets, record the column, recurse with r + 1, then remove them.

Why it works

Each row must hold exactly one queen, so building row by row covers every valid board. Two queens share a diagonal exactly when r - c is equal (top-left to bottom-right) and an anti-diagonal when r + c is equal. Checking these sets rejects a conflicting square immediately, which prunes whole subtrees early rather than discovering the conflict on a complete board. Undoing the choices restores the state for the next column.

Complexity

Time is exponential: bounded by O(n!) placements, and much less in practice because of pruning, with O(n^2) to build each output board. Space O(n) for the sets and recursion, plus the output.

Code

python
def solve_n_queens(n):
    """All boards with n non-attacking queens. Backtracking with O(1) conflict checks."""
    cols, diag, anti = set(), set(), set()    # used column, r - c, r + c
    queens = []                               # queens[r] = column of the queen in row r
    boards = []

    def place(r):
        if r == n:
            boards.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
            return
        for c in range(n):
            if c in cols or (r - c) in diag or (r + c) in anti:
                continue                      # attacked: prune this branch
            cols.add(c)
            diag.add(r - c)
            anti.add(r + c)
            queens.append(c)
            place(r + 1)
            cols.remove(c)
            diag.remove(r - c)
            anti.remove(r + c)
            queens.pop()

    place(0)
    return boards


if __name__ == "__main__":
    assert solve_n_queens(4) == [[".Q..", "...Q", "Q...", "..Q."],
                                 ["..Q.", "Q...", "...Q", ".Q.."]]
    assert solve_n_queens(1) == [["Q"]]
    assert solve_n_queens(2) == [] and solve_n_queens(3) == []
    assert [len(solve_n_queens(n)) for n in range(1, 9)] == [1, 0, 0, 2, 10, 4, 40, 92]
    print("all tests passed")

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

Edge cases

n = 1 has one board. n = 2 and n = 3 have none. The test checks counts up to 8. For counting only, skip building strings; bitmasks for columns and diagonals make it faster still. Symmetry (mirror the first-row choices) halves the work for counting.

Pattern

Backtracking for constraint satisfaction with O(1) feasibility checks. The same structure solves Sudoku, graph colouring, word search on a grid and placing items under constraints.

python
def solve_n_queens(n):
    """All boards with n non-attacking queens. Backtracking with O(1) conflict checks."""
    cols, diag, anti = set(), set(), set()    # used column, r - c, r + c
    queens = []                               # queens[r] = column of the queen in row r
    boards = []

    def place(r):
        if r == n:
            boards.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
            return
        for c in range(n):
            if c in cols or (r - c) in diag or (r + c) in anti:
                continue                      # attacked: prune this branch
            cols.add(c)
            diag.add(r - c)
            anti.add(r + c)
            queens.append(c)
            place(r + 1)
            cols.remove(c)
            diag.remove(r - c)
            anti.remove(r + c)
            queens.pop()

    place(0)
    return boards


if __name__ == "__main__":
    assert solve_n_queens(4) == [[".Q..", "...Q", "Q...", "..Q."],
                                 ["..Q.", "Q...", "...Q", ".Q.."]]
    assert solve_n_queens(1) == [["Q"]]
    assert solve_n_queens(2) == [] and solve_n_queens(3) == []
    assert [len(solve_n_queens(n)) for n in range(1, 9)] == [1, 0, 0, 2, 10, 4, 40, 92]
    print("all tests passed")

Row-by-row backtracking with sets for columns, diagonals (r - c) and anti-diagonals (r + c); checks solution counts for n = 1 to 8.

Complexity

Time: Exponential; bounded by O(n!) placements, much less with pruning. Space: O(n) plus output. Bitmask versions are faster for counting solutions only.

By level

Fresher: Places queens row by row with a safety check and backtracks, tracing n = 4. Should test n = 2 and n = 3.

Mid: Uses O(1) set checks with r - c and r + c and explains pruning. Explains why one queen per row loses no solutions.

Senior: Uses bitmasks and symmetry for counting, discusses constraint propagation and compares with general CSP solvers. Explains how symmetry halves the work.

Key points

  • One queen per row
  • Diagonal key r - c, anti-diagonal key r + c
  • Sets give O(1) conflict checks
  • Undo every choice after recursion
  • Pruning cuts subtrees early

Common mistakes

  • Checking conflicts by scanning the whole board each time
  • Mixing up r - c and r + c
  • Forgetting to remove the queen when backtracking
  • Returning only one solution when all are asked

Follow-ups

  • How would you only count solutions faster?
  • How would you solve Sudoku with the same approach?
  • How can symmetry reduce the work?

Tips

  • Explain the diagonal keys with a small drawing
  • State why one queen per row is safe
  • Test n = 2 and n = 3

Evaluation rubric

  • Correct backtracking and pruning
  • Correct diagonal checks
  • Correct output format
  • Reasonable complexity discussion
50.algorithms-0050Hardsenior

Longest common subsequence: find the length of the longest subsequence shared by two strings and reconstruct one such subsequence.

Let dp[i][j] be the LCS length of the first i characters of a and the first j of b. If the last characters match, dp[i][j] = dp[i-1][j-1] + 1; otherwise it is the larger of dropping one character from either string. Fill the table in O(m x n), then walk back from the bottom-right corner to rebuild one LCS. For the length alone, two rows reduce space to O(min(m, n)).

Full answer

Problem

Given strings a and b, return the length of their longest common subsequence and one such subsequence. A subsequence keeps the order of characters but need not be contiguous.

Example: a = "abcde", b = "ace" gives (3, "ace"). For "ABCBDAB" and "BDCABA" the length is 4 ("BCBA" is one answer; others exist).

Constraints: 0 <= len(a), len(b) <= 1000.

Brute force

Try every subsequence of the shorter string (2^m of them) and check each against the other in O(n): O(n x 2^m). Plain recursion on (i, j) without memoisation is also exponential, because the same pairs are solved many times.

Optimal approach

  1. dp has (m + 1) x (n + 1) cells, with row 0 and column 0 equal to 0 (an empty prefix has LCS 0).
  2. For each i, j:
    • a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1.
    • Otherwise: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).
  3. Reconstruct: from (m, n), on a match add the character and move diagonally; otherwise move towards the larger neighbour. Reverse the collected characters.

Space saving for the length only: keep just the previous and current rows, iterating over the longer string so rows have length min(m, n) + 1.

Why it works

Optimal substructure: if the last characters match, some LCS ends with that character, and the rest is an LCS of the shorter prefixes. If they differ, at least one of them is not in the LCS, so the answer is the better of dropping one or the other. Each cell depends only on cells above and to the left, so filling row by row has all inputs ready. Reconstruction follows the choices that produced each value.

Complexity

O(m x n) time. O(m x n) space for the full table with reconstruction; O(min(m, n)) for length only. Hirschberg's algorithm reconstructs in linear space with divide and conquer.

Code

python
def lcs(a, b):
    """Length and one longest common subsequence of a and b. O(m * n) time and space."""
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]   # dp[i][j] = LCS length of a[:i], b[:j]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    out, i, j = [], m, n                           # walk back to rebuild one answer
    while i and j:
        if a[i - 1] == b[j - 1]:
            out.append(a[i - 1])
            i -= 1
            j -= 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return dp[m][n], "".join(reversed(out))


def lcs_length(a, b):
    """Length only, with two rows: O(m * n) time, O(min(m, n)) space."""
    if len(b) > len(a):
        a, b = b, a
    prev = [0] * (len(b) + 1)
    for x in a:
        cur = [0]
        for j, y in enumerate(b, 1):
            cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1]))
        prev = cur
    return prev[-1]


def is_subsequence(s, t):
    it = iter(t)
    return all(ch in it for ch in s)


if __name__ == "__main__":
    length, seq = lcs("ABCBDAB", "BDCABA")
    assert length == 4 and is_subsequence(seq, "ABCBDAB") and is_subsequence(seq, "BDCABA")
    assert lcs("abcde", "ace") == (3, "ace")
    assert lcs("abc", "def") == (0, "")
    assert lcs("", "abc") == (0, "")
    assert lcs("same", "same") == (4, "same")
    for a, b in [("ABCBDAB", "BDCABA"), ("abcde", "ace"), ("", "x"), ("AGGTAB", "GXTXAYB")]:
        assert lcs_length(a, b) == lcs(a, b)[0]
    assert lcs_length("AGGTAB", "GXTXAYB") == 4
    print("all tests passed")

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

Edge cases

Either string empty gives (0, ""). No common characters. Identical strings return the whole string. When several LCSs exist, tie-breaking in the walk-back decides which one is returned; the test checks validity with is_subsequence rather than one fixed answer.

Pattern

Two-sequence DP on prefixes. Related: edit distance, shortest common supersequence, diff tools (which find an LCS of lines), and DNA sequence alignment.

python
def lcs(a, b):
    """Length and one longest common subsequence of a and b. O(m * n) time and space."""
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]   # dp[i][j] = LCS length of a[:i], b[:j]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    out, i, j = [], m, n                           # walk back to rebuild one answer
    while i and j:
        if a[i - 1] == b[j - 1]:
            out.append(a[i - 1])
            i -= 1
            j -= 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return dp[m][n], "".join(reversed(out))


def lcs_length(a, b):
    """Length only, with two rows: O(m * n) time, O(min(m, n)) space."""
    if len(b) > len(a):
        a, b = b, a
    prev = [0] * (len(b) + 1)
    for x in a:
        cur = [0]
        for j, y in enumerate(b, 1):
            cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1]))
        prev = cur
    return prev[-1]


def is_subsequence(s, t):
    it = iter(t)
    return all(ch in it for ch in s)


if __name__ == "__main__":
    length, seq = lcs("ABCBDAB", "BDCABA")
    assert length == 4 and is_subsequence(seq, "ABCBDAB") and is_subsequence(seq, "BDCABA")
    assert lcs("abcde", "ace") == (3, "ace")
    assert lcs("abc", "def") == (0, "")
    assert lcs("", "abc") == (0, "")
    assert lcs("same", "same") == (4, "same")
    for a, b in [("ABCBDAB", "BDCABA"), ("abcde", "ace"), ("", "x"), ("AGGTAB", "GXTXAYB")]:
        assert lcs_length(a, b) == lcs(a, b)[0]
    assert lcs_length("AGGTAB", "GXTXAYB") == 4
    print("all tests passed")

Full table with reconstruction, a two-row length-only version and an is_subsequence helper used to check the result.

Complexity

Time: O(m * n). Space: O(m * n) with reconstruction; O(min(m, n)) for the length only. Hirschberg's algorithm reconstructs an LCS in linear space.

By level

Fresher: Defines dp on prefixes, writes the recurrence and fills a small table for "abcde" and "ace". Should test an empty string.

Mid: Reconstructs an LCS, reduces space to two rows and explains why several answers can exist. Tests strings with no common characters.

Senior: Relates LCS to edit distance and diff tools, discusses Hirschberg's linear-space method and bit-parallel speedups for long inputs. Can explain why plain recursion without memoisation is exponential.

Key points

  • dp[i][j] is the LCS of the prefixes a[:i] and b[:j]
  • Match: diagonal plus 1; otherwise max of up and left
  • Row 0 and column 0 are 0
  • Walk back from the corner to rebuild
  • Two rows suffice for the length

Common mistakes

  • Confusing subsequence with substring
  • Off-by-one between dp indices and string indices
  • Plain recursion without memoisation
  • Expecting one unique LCS when several exist

Follow-ups

  • How does edit distance differ from LCS?
  • How do diff tools use LCS?
  • How would you find the longest common substring instead?

Tips

  • Define the state in words first
  • Fill a small table on the board
  • Mention the space optimisation

Evaluation rubric

  • Correct recurrence and base cases
  • Correct reconstruction
  • Correct complexity
  • Handles empty strings and ties
51.algorithms-0051Easyfresher

Binary tree traversals: write preorder, inorder and postorder both recursively and with an explicit stack, and explain when each order is useful.

Preorder visits node, left, right; inorder visits left, node, right; postorder visits left, right, node. Recursion is three lines each. The iterative versions use a stack: inorder pushes the left spine then pops and turns right, preorder pushes right before left, and postorder reverses a node-right-left preorder. All are O(n) time and O(h) space, where h is the tree height.

Full answer

Problem

Given the root of a binary tree, return its values in preorder, inorder and postorder. Write each one twice: recursively and iteratively.

Example: for the tree 4 -> (2 -> 1, 3), (6 -> 5, 7), preorder is [4, 2, 1, 3, 6, 5, 7], inorder is [1, 2, 3, 4, 5, 6, 7] and postorder is [1, 3, 2, 5, 7, 6, 4].

Constraints: up to 10^5 nodes; the tree may be a single long chain, so recursion depth can reach n.

Brute force

The recursive definitions are the baseline: inorder(n) = inorder(n.left) + [n.val] + inorder(n.right). They are correct and O(n) visits, but list concatenation copies results (O(n^2) in the worst case for a chain), and Python's default recursion limit of 1,000 breaks on deep trees.

Optimal approach

Use an explicit stack and append into one output list.

  • Inorder: push nodes while walking left; pop one, record it, then move to its right child.
  • Preorder: pop a node, record it, push its right child, then its left child, so the left is processed first.
  • Postorder: run preorder with the child order swapped (node, right, left) and reverse the output.

Why it works

The stack holds exactly the ancestors whose own value or right subtree is still pending, which is what the call stack holds in the recursive version. In inorder, a node is popped only after its entire left subtree has been recorded, which matches "left, node, right". Reversing node-right-left gives left-right-node, which is postorder.

Complexity

Each node is pushed and popped once: O(n) time. The stack holds at most one root-to-leaf path: O(h) space, which is O(log n) for a balanced tree and O(n) for a chain.

Code

python
class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def preorder(root):
    return [] if not root else [root.val] + preorder(root.left) + preorder(root.right)


def inorder(root):
    return [] if not root else inorder(root.left) + [root.val] + inorder(root.right)


def postorder(root):
    return [] if not root else postorder(root.left) + postorder(root.right) + [root.val]


def inorder_iterative(root):
    """Explicit stack: no recursion limit on deep trees. O(n) time, O(h) space."""
    out, stack, node = [], [], root
    while stack or node:
        while node:                      # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right
    return out


def preorder_iterative(root):
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)     # pushed first so left is processed first
        if node.left:
            stack.append(node.left)
    return out


def postorder_iterative(root):
    """Reverse of a root-right-left preorder."""
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return out[::-1]


if __name__ == "__main__":
    #        4
    #      2   6
    #     1 3 5 7
    t = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7)))
    assert preorder(t) == preorder_iterative(t) == [4, 2, 1, 3, 6, 5, 7]
    assert inorder(t) == inorder_iterative(t) == [1, 2, 3, 4, 5, 6, 7]
    assert postorder(t) == postorder_iterative(t) == [1, 3, 2, 5, 7, 6, 4]
    assert inorder(None) == inorder_iterative(None) == preorder_iterative(None) == []
    deep = None
    for v in range(5000):                # a 5,000-deep chain: recursion would fail
        deep = TreeNode(v, deep)
    assert inorder_iterative(deep) == list(range(5000))
    print("all tests passed")

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

Edge cases

Empty tree returns []. A single node. A chain of 5,000 nodes (the iterative version handles it; the recursive one would exceed the default limit). Duplicate values do not change the order.

Pattern

Depth-first traversal with an explicit stack. Inorder of a BST gives sorted order (used in validation and kth-smallest); preorder is the natural order to serialize or copy a tree; postorder computes values that depend on children, such as heights, sizes and deletion.

python
class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def preorder(root):
    return [] if not root else [root.val] + preorder(root.left) + preorder(root.right)


def inorder(root):
    return [] if not root else inorder(root.left) + [root.val] + inorder(root.right)


def postorder(root):
    return [] if not root else postorder(root.left) + postorder(root.right) + [root.val]


def inorder_iterative(root):
    """Explicit stack: no recursion limit on deep trees. O(n) time, O(h) space."""
    out, stack, node = [], [], root
    while stack or node:
        while node:                      # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right
    return out


def preorder_iterative(root):
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)     # pushed first so left is processed first
        if node.left:
            stack.append(node.left)
    return out


def postorder_iterative(root):
    """Reverse of a root-right-left preorder."""
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return out[::-1]


if __name__ == "__main__":
    #        4
    #      2   6
    #     1 3 5 7
    t = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7)))
    assert preorder(t) == preorder_iterative(t) == [4, 2, 1, 3, 6, 5, 7]
    assert inorder(t) == inorder_iterative(t) == [1, 2, 3, 4, 5, 6, 7]
    assert postorder(t) == postorder_iterative(t) == [1, 3, 2, 5, 7, 6, 4]
    assert inorder(None) == inorder_iterative(None) == preorder_iterative(None) == []
    deep = None
    for v in range(5000):                # a 5,000-deep chain: recursion would fail
        deep = TreeNode(v, deep)
    assert inorder_iterative(deep) == list(range(5000))
    print("all tests passed")

Recursive one-liners plus stack-based versions that survive deep trees; a 5,000-node chain is part of the tests.

Complexity

Time: O(n). Space: O(h) stack, h = tree height. The recursive list-concatenation version is O(n^2) on a chain because of copying; appending into one list avoids that.

By level

Fresher: Writes the recursive versions and the iterative inorder, and traces them on a small tree. Explains why the stack is needed for deep trees.

Mid: Writes all three iterative versions cleanly and states O(h) space with best and worst case heights. Connects each order to a real use such as BST sorting, serialization or computing subtree sizes.

Senior: Discusses Morris traversal for O(1) space and its temporary pointer rewiring, and when that trade-off is acceptable. Notes how traversal order affects cache behaviour and how iterators over trees expose lazy traversal in library code.

Key points

  • Preorder node-left-right, inorder left-node-right, postorder left-right-node
  • The explicit stack mirrors the call stack
  • Push right before left for iterative preorder
  • Postorder is a reversed node-right-left preorder
  • O(n) time and O(h) space

Common mistakes

  • Pushing left before right in iterative preorder
  • Forgetting to move to the right child after popping in inorder
  • Relying on recursion for trees that can be 10^5 deep
  • Building results with list concatenation in a loop

Follow-ups

  • How would you do inorder in O(1) extra space (Morris traversal)?
  • Which traversal would you use to delete a tree, and why?
  • How do you rebuild a tree from preorder and inorder?

Tips

  • Draw a 7-node tree and write all three orders before coding
  • State the height-based space bound, not just O(n)
  • Mention the recursion limit for Python

Evaluation rubric

  • Correct three orders
  • Working iterative version
  • Correct complexity in terms of height
  • Knows a use case for each order
52.algorithms-0052Easyfresher

Maximum depth of a binary tree: return the number of nodes on the longest root-to-leaf path, with a recursive and a breadth-first solution.

The depth of a tree is 1 plus the larger depth of its two subtrees, and an empty tree has depth 0. That recursion is O(n) time and O(h) stack. A BFS that counts levels gives the same answer without recursion, using O(width) queue space. Minimum depth is a related trap: a node with one child is not a leaf.

Full answer

Problem

Given the root of a binary tree, return its maximum depth: the number of nodes along the longest path from the root down to a leaf.

Example: the tree 3 -> 9, (20 -> 15, 7) has depth 3.

Constraints: 0 to 10^4 nodes. The tree is not guaranteed to be balanced.

Brute force

Enumerate every root-to-leaf path, measure each one, and take the longest. Collecting paths explicitly costs O(n * h) time and memory because each path is copied.

Optimal approach

Recursive: depth(None) = 0, depth(node) = 1 + max(depth(left), depth(right)).

Iterative: BFS with a queue. Process the queue one level at a time (loop len(q) times), and increase a counter after each level. The counter at the end is the depth.

Why it works

The longest path from a node goes down into whichever subtree is deeper, so the depth of the node is one more than the deeper child. The base case of 0 for an empty subtree makes leaves come out as 1. In BFS every level is fully processed before the next begins, so the number of levels processed equals the depth.

Complexity

Both versions visit each node once: O(n) time. Recursion uses O(h) stack space; BFS uses O(w) where w is the widest level (up to about n/2 in a complete tree).

Code

python
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def max_depth(root):
    """Recursive: depth = 1 + max(child depths). O(n) time, O(h) stack."""
    if root is None:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))


def max_depth_bfs(root):
    """Level by level with a queue; no recursion. O(n) time, O(width) space."""
    if root is None:
        return 0
    depth, q = 0, deque([root])
    while q:
        depth += 1
        for _ in range(len(q)):
            node = q.popleft()
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
    return depth


def min_depth(root):
    """Shortest root-to-leaf path: a node with one child is not a leaf."""
    if root is None:
        return 0
    if not root.left or not root.right:
        return 1 + min_depth(root.left or root.right)
    return 1 + min(min_depth(root.left), min_depth(root.right))


if __name__ == "__main__":
    t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    for f in (max_depth, max_depth_bfs):
        assert f(t) == 3
        assert f(None) == 0
        assert f(TreeNode(1)) == 1
        assert f(TreeNode(1, None, TreeNode(2, None, TreeNode(3)))) == 3
    assert min_depth(t) == 2
    assert min_depth(TreeNode(1, TreeNode(2))) == 2      # not 1: the root is not a leaf
    chain = None
    for v in range(3000):
        chain = TreeNode(v, chain)
    assert max_depth_bfs(chain) == 3000
    print("all tests passed")

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

Edge cases

Empty tree (0). Single node (1). A right-only chain (depth equals n; the BFS version avoids deep recursion). For minimum depth, a node with only one child must recurse into that child; taking min with the empty side would wrongly return 1.

Pattern

Post-order "combine children" recursion: compute a value for each subtree and merge at the parent. The same template gives subtree size, balanced-tree checks, diameter and maximum path sum.

python
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def max_depth(root):
    """Recursive: depth = 1 + max(child depths). O(n) time, O(h) stack."""
    if root is None:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))


def max_depth_bfs(root):
    """Level by level with a queue; no recursion. O(n) time, O(width) space."""
    if root is None:
        return 0
    depth, q = 0, deque([root])
    while q:
        depth += 1
        for _ in range(len(q)):
            node = q.popleft()
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
    return depth


def min_depth(root):
    """Shortest root-to-leaf path: a node with one child is not a leaf."""
    if root is None:
        return 0
    if not root.left or not root.right:
        return 1 + min_depth(root.left or root.right)
    return 1 + min(min_depth(root.left), min_depth(root.right))


if __name__ == "__main__":
    t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    for f in (max_depth, max_depth_bfs):
        assert f(t) == 3
        assert f(None) == 0
        assert f(TreeNode(1)) == 1
        assert f(TreeNode(1, None, TreeNode(2, None, TreeNode(3)))) == 3
    assert min_depth(t) == 2
    assert min_depth(TreeNode(1, TreeNode(2))) == 2      # not 1: the root is not a leaf
    chain = None
    for v in range(3000):
        chain = TreeNode(v, chain)
    assert max_depth_bfs(chain) == 3000
    print("all tests passed")

Recursive and level-by-level versions; min_depth is included to show the one-child trap.

Complexity

Time: O(n). Space: O(h) recursive, O(w) BFS. h is the height and w the maximum width; for a balanced tree h is O(log n) but w is O(n).

By level

Fresher: Writes the three-line recursion with the correct base case and walks through a small example. Can also count levels with a queue.

Mid: Compares DFS and BFS space in terms of height and width and picks one for a given tree shape. Handles minimum depth correctly and extends the idea to a balanced-tree check.

Senior: Explains when BFS finds minimum depth faster because it can stop at the first leaf, which matters for wide but shallow trees. Discusses iterative DFS with an explicit (node, depth) stack and the memory profile of each choice on large trees.

Key points

  • depth = 1 + max(left, right), empty tree = 0
  • BFS counts levels by processing len(q) nodes per round
  • Both are O(n) time
  • Space depends on height (DFS) or width (BFS)
  • Minimum depth needs the one-child rule

Common mistakes

  • Returning 1 for an empty tree
  • Counting edges instead of nodes without saying so
  • Using min with an empty child for minimum depth
  • Forgetting the recursion limit for chain-shaped trees

Follow-ups

  • How do you check whether a tree is height-balanced in one pass?
  • How would you compute the minimum depth efficiently on a very wide tree?
  • What changes for an n-ary tree?

Tips

  • Say whether depth counts nodes or edges
  • Mention the BFS version as the answer to deep trees
  • Give the space bound in terms of h and w

Evaluation rubric

  • Correct recursion and base case
  • Working BFS level count
  • Correct space analysis
  • Handles the minimum-depth variant
53.algorithms-0053Mediumfresher

Validate a binary search tree: decide whether every node is strictly greater than all values in its left subtree and strictly less than all values in its right subtree.

Pass down an allowed range: the root may be anything, a left child must be below its parent, a right child above, and every descendant inherits all ancestor limits. That is O(n) time and O(h) space. Equivalently, an inorder traversal of a valid BST is strictly increasing. Checking only parent and child is the classic wrong answer.

Full answer

Problem

Given the root of a binary tree, return whether it is a valid binary search tree. Every value in the left subtree must be strictly less than the node, and every value in the right subtree strictly greater. Duplicates make the tree invalid in this version.

Example: 5 -> (3 -> 2, 4), (8 -> 7, 9) is valid. 5 -> 3, (8 -> 4, 9) is invalid, because 4 sits in the right subtree of 5.

Constraints: up to 10^4 nodes, values fit in a 64-bit integer.

Brute force

For every node, scan its whole left subtree for the maximum and its whole right subtree for the minimum, and compare. That is O(n^2) on a chain.

A tempting shortcut is to compare each node only with its two children. It is wrong: in the invalid example above, 4 < 8 so the local check passes, but 4 < 5 breaks the rule for the root.

Optimal approach

Recurse with bounds (low, high), starting with (-inf, inf). A node is valid if low < val < high; recurse left with (low, val) and right with (val, high).

Alternative: iterative inorder traversal, tracking the previous value; fail if any value is not greater than the previous one.

Why it works

The BST property says every node must lie between its nearest ancestor where the path turned right (lower bound) and its nearest ancestor where the path turned left (upper bound). Passing bounds down carries exactly those two values. For the inorder version, a binary tree is a BST exactly when its inorder sequence is strictly increasing.

Complexity

O(n) time, each node checked once. O(h) space for recursion or the stack.

Code

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def is_valid_bst(root, low=float("-inf"), high=float("inf")):
    """Every node must lie strictly inside the (low, high) range set by its ancestors."""
    if root is None:
        return True
    if not low < root.val < high:
        return False
    return is_valid_bst(root.left, low, root.val) and is_valid_bst(root.right, root.val, high)


def is_valid_bst_inorder(root):
    """Inorder traversal of a BST is strictly increasing. Iterative, O(n) time, O(h) space."""
    prev, stack, node = None, [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        if prev is not None and node.val <= prev:
            return False
        prev = node.val
        node = node.right
    return True


def wrong_local_check(root):
    """Common mistake: only compare each node with its direct children."""
    if root is None:
        return True
    if root.left and root.left.val >= root.val:
        return False
    if root.right and root.right.val <= root.val:
        return False
    return wrong_local_check(root.left) and wrong_local_check(root.right)


def brute(root):
    vals = []

    def walk(n):
        if n:
            walk(n.left)
            vals.append(n.val)
            walk(n.right)
    walk(root)
    return all(a < b for a, b in zip(vals, vals[1:]))


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.25:
        return None
    return TreeNode(rng.randint(0, 9), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    good = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(8, TreeNode(7), TreeNode(9)))
    trap = TreeNode(5, TreeNode(3), TreeNode(8, TreeNode(4), TreeNode(9)))   # 4 is right of 5
    dup = TreeNode(2, TreeNode(2))
    for f in (is_valid_bst, is_valid_bst_inorder):
        assert f(good) and not f(trap) and not f(dup) and f(None) and f(TreeNode(1))
    assert wrong_local_check(trap)                     # the local check is fooled
    rng = random.Random(51)
    for _ in range(3000):
        t = random_tree(rng, 4)
        assert is_valid_bst(t) == is_valid_bst_inorder(t) == brute(t)
    print("all tests passed")

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

Edge cases

Empty tree is valid. Single node. Duplicates (invalid here; some definitions allow them on one side, so ask). Values equal to the integer limits: using -inf and inf (or None bounds) avoids sentinel bugs that appear when a language uses INT_MIN as the sentinel.

Pattern

Top-down state passing: carry constraints from ancestors into the recursion. The same approach handles "is this a valid heap", range-limited tree queries, and path-dependent checks.

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def is_valid_bst(root, low=float("-inf"), high=float("inf")):
    """Every node must lie strictly inside the (low, high) range set by its ancestors."""
    if root is None:
        return True
    if not low < root.val < high:
        return False
    return is_valid_bst(root.left, low, root.val) and is_valid_bst(root.right, root.val, high)


def is_valid_bst_inorder(root):
    """Inorder traversal of a BST is strictly increasing. Iterative, O(n) time, O(h) space."""
    prev, stack, node = None, [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        if prev is not None and node.val <= prev:
            return False
        prev = node.val
        node = node.right
    return True


def wrong_local_check(root):
    """Common mistake: only compare each node with its direct children."""
    if root is None:
        return True
    if root.left and root.left.val >= root.val:
        return False
    if root.right and root.right.val <= root.val:
        return False
    return wrong_local_check(root.left) and wrong_local_check(root.right)


def brute(root):
    vals = []

    def walk(n):
        if n:
            walk(n.left)
            vals.append(n.val)
            walk(n.right)
    walk(root)
    return all(a < b for a, b in zip(vals, vals[1:]))


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.25:
        return None
    return TreeNode(rng.randint(0, 9), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    good = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(8, TreeNode(7), TreeNode(9)))
    trap = TreeNode(5, TreeNode(3), TreeNode(8, TreeNode(4), TreeNode(9)))   # 4 is right of 5
    dup = TreeNode(2, TreeNode(2))
    for f in (is_valid_bst, is_valid_bst_inorder):
        assert f(good) and not f(trap) and not f(dup) and f(None) and f(TreeNode(1))
    assert wrong_local_check(trap)                     # the local check is fooled
    rng = random.Random(51)
    for _ in range(3000):
        t = random_tree(rng, 4)
        assert is_valid_bst(t) == is_valid_bst_inorder(t) == brute(t)
    print("all tests passed")

Bounds recursion, iterative inorder, the wrong local check (shown failing), and a random cross-check against sorted-inorder.

Complexity

Time: O(n). Space: O(h). Inorder can stop at the first violation, so invalid trees often finish early.

By level

Fresher: Writes the bounds recursion and explains with a counterexample why checking only children fails. Knows that inorder output of a BST is sorted.

Mid: Implements the iterative inorder check with one previous value and discusses sentinel pitfalls. Handles a duplicates policy given by the interviewer.

Senior: Extends to recovering a BST with two swapped nodes using the inorder inversion pattern. Discusses validating very large or persisted trees in a streaming way, checking each node once with bounded memory.

Key points

  • Every node must satisfy bounds from all ancestors, not just its parent
  • Pass (low, high) down the recursion
  • Inorder of a BST is strictly increasing
  • Use infinities or None for bounds, not integer sentinels
  • O(n) time, O(h) space

Common mistakes

  • Comparing only with direct children
  • Using <= and allowing duplicates without asking
  • Using INT_MIN/INT_MAX as sentinels when node values can equal them
  • Storing the whole inorder list when one previous value is enough

Follow-ups

  • How would you recover a BST where exactly two nodes were swapped?
  • How do you allow duplicates on the left side only?
  • How would you validate a BST stored in an array?

Tips

  • Show the counterexample that breaks the local check
  • Ask how duplicates are treated
  • Offer both the bounds and the inorder method

Evaluation rubric

  • Correct global constraint
  • Correct handling of duplicates and limits
  • O(n) time
  • Explains the counterexample
54.algorithms-0054Mediumfresher

Binary tree level order traversal: return node values grouped by depth, then adapt the solution for zigzag order and the right-side view.

Use a queue and process it one level at a time: read the queue length, pop exactly that many nodes, collect their values and push their children. That yields one list per level in O(n) time and O(w) space. Zigzag reverses every other level, and the right-side view takes the last value of each level.

Full answer

Problem

Given the root of a binary tree, return a list of levels, each holding that level's values from left to right.

Example: 3 -> 9, (20 -> 15, 7) gives [[3], [9, 20], [15, 7]]. Zigzag order gives [[3], [20, 9], [15, 7]], and the right-side view gives [3, 20, 7].

Constraints: 0 to 2,000 nodes; values are any integers.

Brute force

Compute the height h, then for each depth d run a separate DFS that collects nodes at depth d. That is O(n * h) time, O(n^2) on a chain.

Optimal approach

BFS with a deque. While the queue is not empty, take size = len(q), pop size nodes, append their values to a new list, and push their non-null children. Append the list to the result.

Variants are post-processing steps: reverse odd-indexed levels for zigzag; take level[-1] for the right-side view.

Why it works

BFS visits nodes in order of distance from the root. At the start of each round the queue holds exactly the nodes of one level, because all nodes of the previous level were popped in the previous round and only their children were pushed. Freezing len(q) before the inner loop keeps children from being mixed into the current level.

Complexity

O(n) time: each node enters and leaves the queue once. O(w) extra space for the queue, where w is the maximum width; output is O(n).

Code

python
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def level_order(root):
    """Return values level by level. BFS with a queue; O(n) time, O(width) space."""
    if root is None:
        return []
    levels, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):          # exactly the nodes of the current level
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        levels.append(level)
    return levels


def zigzag(root):
    return [lvl if i % 2 == 0 else lvl[::-1] for i, lvl in enumerate(level_order(root))]


def right_side_view(root):
    return [lvl[-1] for lvl in level_order(root)]


def level_order_dfs(root):
    """Reference: DFS that records depth."""
    out = []

    def walk(n, d):
        if n:
            if d == len(out):
                out.append([])
            out[d].append(n.val)
            walk(n.left, d + 1)
            walk(n.right, d + 1)
    walk(root, 0)
    return out


if __name__ == "__main__":
    t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    assert level_order(t) == level_order_dfs(t) == [[3], [9, 20], [15, 7]]
    assert zigzag(t) == [[3], [20, 9], [15, 7]]
    assert right_side_view(t) == [3, 20, 7]
    assert level_order(None) == [] and level_order(TreeNode(1)) == [[1]]
    lopsided = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
    assert right_side_view(lopsided) == [1, 3, 4]
    print("all tests passed")

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

Edge cases

Empty tree returns []. Single node. A lopsided tree where the right-side view must show a left node at the deepest level (the test with 1 -> (2 -> 4), 3 returns [1, 3, 4]). Deep chains are fine because BFS does not recurse.

Pattern

Level-by-level BFS using the queue size as a boundary. The same skeleton solves minimum depth, average of levels, connecting next pointers, and multi-source grid problems such as rotting oranges.

python
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def level_order(root):
    """Return values level by level. BFS with a queue; O(n) time, O(width) space."""
    if root is None:
        return []
    levels, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):          # exactly the nodes of the current level
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        levels.append(level)
    return levels


def zigzag(root):
    return [lvl if i % 2 == 0 else lvl[::-1] for i, lvl in enumerate(level_order(root))]


def right_side_view(root):
    return [lvl[-1] for lvl in level_order(root)]


def level_order_dfs(root):
    """Reference: DFS that records depth."""
    out = []

    def walk(n, d):
        if n:
            if d == len(out):
                out.append([])
            out[d].append(n.val)
            walk(n.left, d + 1)
            walk(n.right, d + 1)
    walk(root, 0)
    return out


if __name__ == "__main__":
    t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    assert level_order(t) == level_order_dfs(t) == [[3], [9, 20], [15, 7]]
    assert zigzag(t) == [[3], [20, 9], [15, 7]]
    assert right_side_view(t) == [3, 20, 7]
    assert level_order(None) == [] and level_order(TreeNode(1)) == [[1]]
    lopsided = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
    assert right_side_view(lopsided) == [1, 3, 4]
    print("all tests passed")

BFS with a frozen level size, plus zigzag and right-side view, cross-checked against a depth-tracking DFS.

Complexity

Time: O(n). Space: O(w) queue plus O(n) output. For a complete tree the last level holds about n/2 nodes, so queue space can be O(n).

By level

Fresher: Writes the BFS with the level-size loop and traces it on a small tree. Explains why a deque is used instead of a list.

Mid: Adapts the same code to zigzag, right-side view and bottom-up order without rewriting the traversal. Compares the BFS and depth-tagged DFS approaches.

Senior: Discusses memory on very wide trees and when a DFS with depth tags is cheaper. Relates level order to batch processing by distance, such as layered dependency resolution or friend-of-friend expansion in graphs.

Key points

  • Freeze len(q) to separate levels
  • Each node enqueued and dequeued once
  • Zigzag = reverse odd levels
  • Right-side view = last of each level
  • DFS with a depth index gives the same groups

Common mistakes

  • Using len(q) inside the loop so it changes as children are pushed
  • Using a list with pop(0), which is O(n) per pop
  • Pushing None children and then crashing on .val
  • Reversing the queue for zigzag instead of the output

Follow-ups

  • How do you return levels bottom-up?
  • How would you connect each node to its right neighbour on the same level?
  • Can this run with O(1) extra space on a perfect tree?

Tips

  • Mention collections.deque for O(1) pops
  • Show how a variant is just post-processing
  • State space in terms of width

Evaluation rubric

  • Correct grouping by level
  • Uses an O(1)-pop queue
  • Handles variants
  • Correct complexity
55.algorithms-0055Mediummid

Lowest common ancestor: given two nodes of a binary tree, find their deepest shared ancestor, and show the faster method when the tree is a BST.

Recurse: if the current node is null or equals p or q, return it. Otherwise search both children; if both return non-null, the current node is the LCA, else pass up whichever side found something. That is O(n) time and O(h) space. In a BST, walk from the root, going left while both values are smaller and right while both are larger; the first split point is the LCA in O(h).

Full answer

Problem

Given the root of a binary tree and two nodes p and q that exist in it, return their lowest common ancestor: the deepest node that has both p and q as descendants. A node counts as a descendant of itself.

Example: in the tree 3 -> (5 -> 6, (2 -> 7, 4)), (1 -> 0, 8), LCA(5, 1) is 3, LCA(5, 4) is 5, and LCA(7, 4) is 2.

Constraints: up to 10^5 nodes, values unique, both nodes present.

Brute force

Find the root-to-p path and the root-to-q path, then walk both from the start and return the last shared node. This is O(n) time but needs O(h) memory for two stored paths and two separate searches.

Optimal approach

One recursive pass:

  1. If root is None, p or q, return root.
  2. left = lca(root.left), right = lca(root.right).
  3. If both are non-null, p and q are in different subtrees, so return root.
  4. Otherwise return the non-null side.

For a BST, use values: while both are smaller than the node go left, while both are larger go right, otherwise return the node.

Why it works

Each call returns p, q, the LCA, or None for its subtree. The first node where p and q come back from different sides is the point where their paths diverge, which is the deepest common ancestor. If one of them is an ancestor of the other, the recursion returns it as soon as it is reached, which is correct because a node is its own descendant. In a BST, the split point is the first node whose value lies between p and q.

Complexity

General tree: O(n) time, O(h) recursion. BST: O(h) time and O(1) extra space with the loop.

Code

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def lca(root, p, q):
    """Lowest common ancestor of nodes p and q in any binary tree. O(n) time, O(h) space."""
    if root is None or root is p or root is q:
        return root
    left, right = lca(root.left, p, q), lca(root.right, p, q)
    if left and right:
        return root                      # p and q are on different sides
    return left or right


def lca_bst(root, p, q):
    """In a BST, walk down: both smaller go left, both larger go right. O(h)."""
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node


def brute(root, p, q):
    """Compare root-to-node paths; the last shared node is the LCA."""
    def path(n, target, acc):
        if n is None:
            return None
        acc = acc + [n]
        if n is target:
            return acc
        return path(n.left, target, acc) or path(n.right, target, acc)
    a, b = path(root, p, []), path(root, q, [])
    shared = None
    for x, y in zip(a, b):
        if x is not y:
            break
        shared = x
    return shared


def insert(root, v):
    if root is None:
        return TreeNode(v)
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def nodes(root):
    return [] if root is None else [root] + nodes(root.left) + nodes(root.right)


if __name__ == "__main__":
    n5, n1, n6, n2, n0, n8, n7, n4 = (TreeNode(v) for v in (5, 1, 6, 2, 0, 8, 7, 4))
    root = TreeNode(3, n5, n1)
    n5.left, n5.right, n1.left, n1.right = n6, n2, n0, n8
    n2.left, n2.right = n7, n4
    assert lca(root, n5, n1) is root
    assert lca(root, n5, n4) is n5                  # a node is its own ancestor
    assert lca(root, n7, n4) is n2
    rng = random.Random(55)
    for _ in range(300):
        bst = None
        for v in rng.sample(range(100), rng.randint(1, 15)):
            bst = insert(bst, v)
        all_nodes = nodes(bst)
        p, q = rng.choice(all_nodes), rng.choice(all_nodes)
        assert lca(bst, p, q) is lca_bst(bst, p, q) is brute(bst, p, q)
    print("all tests passed")

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

Edge cases

p equals q (returns p). One node is the ancestor of the other. Nodes not present (the basic version assumes presence; to handle absence, count how many were found and return None if fewer than two). Compare nodes by identity when values may repeat.

Pattern

Bottom-up information passing in a tree. Variants include LCA with parent pointers (two-pointer walk like linked-list intersection), many queries on a static tree (binary lifting or Euler tour plus range minimum), and distance between two nodes as depth(p) + depth(q) - 2 * depth(lca).

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def lca(root, p, q):
    """Lowest common ancestor of nodes p and q in any binary tree. O(n) time, O(h) space."""
    if root is None or root is p or root is q:
        return root
    left, right = lca(root.left, p, q), lca(root.right, p, q)
    if left and right:
        return root                      # p and q are on different sides
    return left or right


def lca_bst(root, p, q):
    """In a BST, walk down: both smaller go left, both larger go right. O(h)."""
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node


def brute(root, p, q):
    """Compare root-to-node paths; the last shared node is the LCA."""
    def path(n, target, acc):
        if n is None:
            return None
        acc = acc + [n]
        if n is target:
            return acc
        return path(n.left, target, acc) or path(n.right, target, acc)
    a, b = path(root, p, []), path(root, q, [])
    shared = None
    for x, y in zip(a, b):
        if x is not y:
            break
        shared = x
    return shared


def insert(root, v):
    if root is None:
        return TreeNode(v)
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def nodes(root):
    return [] if root is None else [root] + nodes(root.left) + nodes(root.right)


if __name__ == "__main__":
    n5, n1, n6, n2, n0, n8, n7, n4 = (TreeNode(v) for v in (5, 1, 6, 2, 0, 8, 7, 4))
    root = TreeNode(3, n5, n1)
    n5.left, n5.right, n1.left, n1.right = n6, n2, n0, n8
    n2.left, n2.right = n7, n4
    assert lca(root, n5, n1) is root
    assert lca(root, n5, n4) is n5                  # a node is its own ancestor
    assert lca(root, n7, n4) is n2
    rng = random.Random(55)
    for _ in range(300):
        bst = None
        for v in rng.sample(range(100), rng.randint(1, 15)):
            bst = insert(bst, v)
        all_nodes = nodes(bst)
        p, q = rng.choice(all_nodes), rng.choice(all_nodes)
        assert lca(bst, p, q) is lca_bst(bst, p, q) is brute(bst, p, q)
    print("all tests passed")

General recursive LCA, the BST walk, and a path-comparison brute force; random BSTs cross-check all three.

Complexity

Time: O(n) general, O(h) BST. Space: O(h) general, O(1) BST loop. For many queries on a fixed tree, binary lifting gives O(log n) per query after O(n log n) preprocessing.

By level

Fresher: Explains the path-comparison approach and then the recursive version on the sample tree. Handles the case where one node is an ancestor of the other.

Mid: Writes the single-pass recursion and the BST walk, and states what each call returns. Handles missing nodes by counting how many were found.

Senior: Discusses binary lifting or Euler tour with sparse tables for heavy query loads and the preprocessing cost. Connects LCA to practical uses such as version-control merge bases and shortest paths in hierarchies.

Key points

  • Return p, q, LCA or None from each subtree
  • Both sides non-null means the current node is the split
  • A node is its own ancestor
  • BST: move toward the side containing both values
  • Distance = depth(p) + depth(q) - 2 * depth(lca)

Common mistakes

  • Returning early before checking both sides when it matters for presence checks
  • Comparing by value when values are not unique
  • Using the BST shortcut on a general tree
  • Assuming both nodes exist when the interviewer did not say so

Follow-ups

  • How do you handle the case where one node might be missing?
  • How would you answer a million LCA queries on a fixed tree?
  • What if nodes have parent pointers and the root is unknown?

Tips

  • Clarify presence and uniqueness first
  • Explain what each recursive call returns
  • Mention the BST speed-up if the tree is ordered

Evaluation rubric

  • Correct single-pass recursion
  • Handles ancestor-of-itself case
  • Knows the BST and parent-pointer variants
  • Correct complexity
56.algorithms-0056Easyfresher

Diameter of a binary tree: find the number of edges on the longest path between any two nodes, which may not pass through the root.

For every node, the longest path that bends there is the left height plus the right height. Compute heights in one post-order pass and keep a running maximum of left plus right. That is O(n) time and O(h) space. Recomputing heights from every node is the O(n^2) brute force.

Full answer

Problem

Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes.

Example: 1 -> (2 -> 4, 5), 3 has diameter 3 (the path 4, 2, 1, 3). In 1 -> (2 -> (3 -> 4), (5 -> -, 6)) the longest path is 4, 3, 2, 5, 6 with 4 edges, and it does not touch the root.

Constraints: 1 to 10^4 nodes.

Brute force

For each node, compute the height of its left and right subtrees separately and take the best left + right over all nodes. Each height call is O(n), so the total is O(n^2) on a chain.

Optimal approach

One post-order DFS where height(node) returns the number of nodes on the longest downward path. At each node, after getting lh and rh, update best = max(best, lh + rh) and return 1 + max(lh, rh).

Why it works

Every path in a tree has exactly one highest node, where it bends. The longest path bending at a node goes down the deepest branch on each side, so its edge count is lh + rh when heights count nodes. Checking every node as the bend point covers every path, and computing heights bottom-up means each is computed once.

Complexity

O(n) time, O(h) recursion space.

Code

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def diameter(root):
    """Longest path (in edges) between any two nodes. One post-order pass, O(n)."""
    best = 0

    def height(node):                    # number of nodes on the longest downward path
        nonlocal best
        if node is None:
            return 0
        lh, rh = height(node.left), height(node.right)
        best = max(best, lh + rh)        # path that bends at this node
        return 1 + max(lh, rh)

    height(root)
    return best


def brute(root):
    """O(n^2): for each node, recompute heights of both subtrees."""
    def h(n):
        return 0 if n is None else 1 + max(h(n.left), h(n.right))

    def walk(n):
        if n is None:
            return 0
        return max(h(n.left) + h(n.right), walk(n.left), walk(n.right))
    return walk(root)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return None
    return TreeNode(0, random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
    assert diameter(t) == 3                         # 4 -> 2 -> 1 -> 3
    assert diameter(None) == 0 and diameter(TreeNode(1)) == 0
    # longest path does not pass through the root
    side = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4)), TreeNode(5, None, TreeNode(6))))
    assert diameter(side) == 4
    rng = random.Random(56)
    for _ in range(2000):
        r = random_tree(rng, 6)
        assert diameter(r) == brute(r)
    print("all tests passed")

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

Edge cases

Empty tree or single node: diameter 0. A chain: diameter n - 1. The path does not pass through the root (covered by the second example). Be explicit about edges versus nodes; some versions count nodes, which is one more.

Pattern

Return one value to the parent (height) while updating a global answer from both children (the bend). The same structure solves binary tree maximum path sum, longest univalue path, and tree diameter in graphs (or two BFS passes in an unweighted tree).

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def diameter(root):
    """Longest path (in edges) between any two nodes. One post-order pass, O(n)."""
    best = 0

    def height(node):                    # number of nodes on the longest downward path
        nonlocal best
        if node is None:
            return 0
        lh, rh = height(node.left), height(node.right)
        best = max(best, lh + rh)        # path that bends at this node
        return 1 + max(lh, rh)

    height(root)
    return best


def brute(root):
    """O(n^2): for each node, recompute heights of both subtrees."""
    def h(n):
        return 0 if n is None else 1 + max(h(n.left), h(n.right))

    def walk(n):
        if n is None:
            return 0
        return max(h(n.left) + h(n.right), walk(n.left), walk(n.right))
    return walk(root)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return None
    return TreeNode(0, random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
    assert diameter(t) == 3                         # 4 -> 2 -> 1 -> 3
    assert diameter(None) == 0 and diameter(TreeNode(1)) == 0
    # longest path does not pass through the root
    side = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4)), TreeNode(5, None, TreeNode(6))))
    assert diameter(side) == 4
    rng = random.Random(56)
    for _ in range(2000):
        r = random_tree(rng, 6)
        assert diameter(r) == brute(r)
    print("all tests passed")

One post-order pass with a nonlocal best, cross-checked against the O(n^2) version on random trees.

Complexity

Time: O(n). Space: O(h). For a general unweighted tree stored as a graph, two BFS passes (farthest from any node, then farthest from that) also give the diameter in O(n).

By level

Fresher: Explains that the longest path bends at some node and computes it with a height helper. Shows a tree where the answer avoids the root.

Mid: Writes the single-pass version with a running maximum and separates the returned value from the answer. Extends it to the weighted maximum path sum.

Senior: Generalizes to trees given as edge lists with the two-BFS argument and explains why it works only for trees. Discusses iterative post-order to avoid recursion limits on deep inputs.

Key points

  • Each path bends at exactly one highest node
  • Path through a node = left height + right height
  • Return height, update the global best
  • O(n) by computing heights once
  • Clarify edges versus nodes

Common mistakes

  • Returning the diameter from the recursion instead of the height
  • Only checking the path through the root
  • Off-by-one between edges and nodes
  • Recomputing heights for every node

Follow-ups

  • How do you find the maximum path sum when nodes have weights?
  • How would you find the diameter of a general tree given as an edge list?
  • How do you return the actual path, not just its length?

Tips

  • Draw a tree where the diameter avoids the root
  • Say clearly what the helper returns
  • Mention the two-BFS method for general trees

Evaluation rubric

  • Correct single-pass algorithm
  • Handles paths not through the root
  • Correct unit (edges)
  • Correct complexity
57.algorithms-0057Hardsenior

Serialize and deserialize a binary tree: convert a tree to a string and rebuild exactly the same shape and values from that string.

Write a preorder traversal with a marker such as '#' for every missing child; the markers make the shape unambiguous. To rebuild, read tokens in the same order with an iterator: a number creates a node and then builds its left and right subtrees, '#' returns None. Both directions are O(n). A level-order format with trailing markers trimmed is the common alternative.

Full answer

Problem

Design serialize(root) -> str and deserialize(s) -> root so that deserialize(serialize(t)) produces a tree with the same structure and values as t.

Example: the tree 1 -> 2, (3 -> 4, 5) can be written as "1,2,#,#,3,4,#,#,5,#,#" in preorder, or "1,2,3,#,#,4,5" in level order.

Constraints: up to 10^4 nodes, values from -1000 to 1000. The format is yours to choose but must be lossless.

Brute force

Store both preorder and inorder sequences and rebuild using the classic two-traversal construction. It works only when values are unique, needs two passes and a hash map, and doubles the output size.

Optimal approach

Preorder with null markers:

  • serialize: visit node, write its value, recurse left, recurse right; write # for None.
  • deserialize: split on commas, wrap in an iterator, and define build(): take the next token; if # return None; otherwise create a node, then set left = build() and right = build().

Level-order variant: BFS writing # for None children, then trim trailing #. Rebuild with a queue, attaching the next two tokens as left and right of each dequeued node.

Why it works

With explicit null markers, every subtree's encoding is self-delimiting: a subtree is either # or a value followed by two complete subtree encodings. That grammar has exactly one parse, so the decoder consumes the same tokens in the same order and rebuilds the same shape. Duplicates are fine because no value lookups are needed.

Complexity

O(n) time each way. Output length is O(n): n values plus n + 1 markers. The recursion depth is O(h); an explicit stack or the BFS version avoids recursion limits on deep chains.

Code

python
import random
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def serialize(root):
    """Preorder with '#' for missing children. O(n) time and output size."""
    out = []

    def walk(node):
        if node is None:
            out.append("#")
            return
        out.append(str(node.val))
        walk(node.left)
        walk(node.right)
    walk(root)
    return ",".join(out)


def deserialize(data):
    tokens = iter(data.split(","))

    def build():
        tok = next(tokens)
        if tok == "#":
            return None
        node = TreeNode(int(tok))
        node.left = build()
        node.right = build()
        return node
    return build()


def serialize_bfs(root):
    """Level order variant (the format many judges print). Trailing '#' trimmed."""
    out, q = [], deque([root])
    while q:
        node = q.popleft()
        if node is None:
            out.append("#")
            continue
        out.append(str(node.val))
        q.append(node.left)
        q.append(node.right)
    while out and out[-1] == "#":
        out.pop()
    return ",".join(out)


def deserialize_bfs(data):
    if not data:
        return None
    toks = data.split(",")
    root = TreeNode(int(toks[0]))
    q, i = deque([root]), 1
    while q and i < len(toks):
        node = q.popleft()
        for side in ("left", "right"):
            if i < len(toks) and toks[i] != "#":
                child = TreeNode(int(toks[i]))
                setattr(node, side, child)
                q.append(child)
            i += 1
    return root


def same(a, b):
    if a is None or b is None:
        return a is b
    return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return None
    return TreeNode(rng.randint(-50, 50), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
    assert serialize(t) == "1,2,#,#,3,4,#,#,5,#,#"
    assert serialize_bfs(t) == "1,2,3,#,#,4,5"
    assert serialize(None) == "#" and deserialize("#") is None
    assert serialize_bfs(None) == "" and deserialize_bfs("") is None
    rng = random.Random(57)
    for _ in range(2000):
        r = random_tree(rng, 6)
        assert same(deserialize(serialize(r)), r)
        assert same(deserialize_bfs(serialize_bfs(r)), r)
    print("all tests passed")

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

Edge cases

Empty tree ("#" in preorder, "" in level order). Negative and multi-digit values (a delimiter is needed). Duplicate values. Very deep chains (prefer BFS or an iterative decoder).

Pattern

Self-delimiting encoding of recursive structures. The same idea underlies parsers for nested data, Merkle tree hashing of subtrees, and detecting duplicate subtrees by serializing each one.

python
import random
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def serialize(root):
    """Preorder with '#' for missing children. O(n) time and output size."""
    out = []

    def walk(node):
        if node is None:
            out.append("#")
            return
        out.append(str(node.val))
        walk(node.left)
        walk(node.right)
    walk(root)
    return ",".join(out)


def deserialize(data):
    tokens = iter(data.split(","))

    def build():
        tok = next(tokens)
        if tok == "#":
            return None
        node = TreeNode(int(tok))
        node.left = build()
        node.right = build()
        return node
    return build()


def serialize_bfs(root):
    """Level order variant (the format many judges print). Trailing '#' trimmed."""
    out, q = [], deque([root])
    while q:
        node = q.popleft()
        if node is None:
            out.append("#")
            continue
        out.append(str(node.val))
        q.append(node.left)
        q.append(node.right)
    while out and out[-1] == "#":
        out.pop()
    return ",".join(out)


def deserialize_bfs(data):
    if not data:
        return None
    toks = data.split(",")
    root = TreeNode(int(toks[0]))
    q, i = deque([root]), 1
    while q and i < len(toks):
        node = q.popleft()
        for side in ("left", "right"):
            if i < len(toks) and toks[i] != "#":
                child = TreeNode(int(toks[i]))
                setattr(node, side, child)
                q.append(child)
            i += 1
    return root


def same(a, b):
    if a is None or b is None:
        return a is b
    return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return None
    return TreeNode(rng.randint(-50, 50), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
    assert serialize(t) == "1,2,#,#,3,4,#,#,5,#,#"
    assert serialize_bfs(t) == "1,2,3,#,#,4,5"
    assert serialize(None) == "#" and deserialize("#") is None
    assert serialize_bfs(None) == "" and deserialize_bfs("") is None
    rng = random.Random(57)
    for _ in range(2000):
        r = random_tree(rng, 6)
        assert same(deserialize(serialize(r)), r)
        assert same(deserialize_bfs(serialize_bfs(r)), r)
    print("all tests passed")

Preorder codec with an iterator-based decoder and a level-order codec; 2,000 random trees round-trip through both.

Complexity

Time: O(n). Space: O(n) output, O(h) recursion. The level-order codec uses O(w) queue space and no recursion.

By level

Fresher: Explains why null markers are needed using two different trees that would otherwise encode the same way. Writes the preorder encoder and follows the decoder on a small example.

Mid: Implements both directions with an iterator, handles empty trees and negatives, and states the O(n) cost. Compares preorder and level-order formats.

Senior: Discusses compact binary formats, versioning a stored format, and decoding untrusted input safely with depth and size limits. Uses subtree serialization to detect duplicate subtrees with hashing.

Key points

  • Null markers make the encoding unambiguous
  • Decode in exactly the same traversal order
  • An iterator over tokens keeps the decoder simple
  • Works with duplicate values
  • Output is O(n)

Common mistakes

  • Omitting null markers so different shapes produce the same string
  • Using string slicing in the decoder, causing O(n^2)
  • No delimiter, breaking multi-digit or negative values
  • Relying on unique values via preorder plus inorder

Follow-ups

  • How would you make the format more compact (binary, varints, bitmap of nulls)?
  • How do you find duplicate subtrees using serialization?
  • How would you serialize an n-ary tree?

Tips

  • State the grammar of the encoding
  • Test the empty tree and negative values
  • Mention BFS to avoid deep recursion

Evaluation rubric

  • Lossless format
  • Correct decoder
  • O(n) both ways
  • Handles empty and negative inputs
58.algorithms-0058Mediummid

Kth smallest element in a BST: return the k-th smallest value, and explain how to support frequent queries on a tree that changes.

Inorder traversal of a BST visits values in ascending order, so run an iterative inorder and stop at the k-th popped node: O(h + k) time and O(h) space. If the tree is modified often and queried often, store each node's subtree size; then the k-th value is found in O(h) by comparing k with the left subtree size.

Full answer

Problem

Given the root of a BST and an integer k (1-indexed), return the k-th smallest value.

Example: inserting 5, 3, 6, 2, 4, 1 gives a BST whose 3rd smallest value is 3.

Constraints: 1 <= k <= n <= 10^4; values are unique. Follow-up: the BST is modified often and kth-smallest is called often.

Brute force

Do a full inorder traversal into a list and return list[k - 1]. Correct, O(n) time and O(n) space, and it ignores that the answer may come early.

Optimal approach

Iterative inorder with early exit: push the left spine, pop a node, decrement k, return when k reaches 0, otherwise move to the right child.

For the follow-up, augment every node with size (nodes in its subtree), maintained on insert and delete. At a node, let L = size(left): if k <= L go left; if k == L + 1 return the node; else set k -= L + 1 and go right.

Why it works

Inorder visits the left subtree (all smaller values), then the node, then the right subtree, so the m-th popped node is the m-th smallest. In the augmented version, L counts exactly the values smaller than the current node within its subtree, so comparing k against L tells which side contains the answer.

Complexity

Early-exit inorder: O(h + k) time, O(h) space. Augmented tree: O(h) per query and O(h) extra work per insert or delete to update sizes; with a balanced tree (red-black, AVL, treap) h is O(log n).

Code

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right
        self.size = 1                    # subtree size, used by the order-statistic version


def kth_smallest(root, k):
    """Iterative inorder that stops at the k-th node. O(h + k) time, O(h) space."""
    stack, node = [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    raise ValueError("k is larger than the tree size")


def insert(root, v):
    """BST insert that maintains subtree sizes."""
    if root is None:
        return TreeNode(v)
    root.size += 1
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def kth_by_size(root, k):
    """O(h) per query when every node stores its subtree size."""
    node = root
    while node:
        left = node.left.size if node.left else 0
        if k <= left:
            node = node.left
        elif k == left + 1:
            return node.val
        else:
            k -= left + 1
            node = node.right
    raise ValueError("k is larger than the tree size")


if __name__ == "__main__":
    root = None
    for v in (5, 3, 6, 2, 4, 1):
        root = insert(root, v)
    assert [kth_smallest(root, k) for k in range(1, 7)] == [1, 2, 3, 4, 5, 6]
    assert kth_by_size(root, 3) == 3
    try:
        kth_smallest(root, 7)
        assert False
    except ValueError:
        pass
    rng = random.Random(58)
    for _ in range(300):
        vals = rng.sample(range(1000), rng.randint(1, 40))
        root = None
        for v in vals:
            root = insert(root, v)
        k = rng.randint(1, len(vals))
        assert kth_smallest(root, k) == kth_by_size(root, k) == sorted(vals)[k - 1]
    print("all tests passed")

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

Edge cases

k = 1 (leftmost node) and k = n (rightmost). k larger than n (raise or return an error). A skewed BST where h = n. Duplicate values, if allowed, need a policy for which side holds equals.

Pattern

Inorder as sorted iteration, plus order-statistic trees for rank queries. The same augmentation answers "how many values are less than x" and supports sliding-window medians with a balanced BST.

python
import random


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right
        self.size = 1                    # subtree size, used by the order-statistic version


def kth_smallest(root, k):
    """Iterative inorder that stops at the k-th node. O(h + k) time, O(h) space."""
    stack, node = [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    raise ValueError("k is larger than the tree size")


def insert(root, v):
    """BST insert that maintains subtree sizes."""
    if root is None:
        return TreeNode(v)
    root.size += 1
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def kth_by_size(root, k):
    """O(h) per query when every node stores its subtree size."""
    node = root
    while node:
        left = node.left.size if node.left else 0
        if k <= left:
            node = node.left
        elif k == left + 1:
            return node.val
        else:
            k -= left + 1
            node = node.right
    raise ValueError("k is larger than the tree size")


if __name__ == "__main__":
    root = None
    for v in (5, 3, 6, 2, 4, 1):
        root = insert(root, v)
    assert [kth_smallest(root, k) for k in range(1, 7)] == [1, 2, 3, 4, 5, 6]
    assert kth_by_size(root, 3) == 3
    try:
        kth_smallest(root, 7)
        assert False
    except ValueError:
        pass
    rng = random.Random(58)
    for _ in range(300):
        vals = rng.sample(range(1000), rng.randint(1, 40))
        root = None
        for v in vals:
            root = insert(root, v)
        k = rng.randint(1, len(vals))
        assert kth_smallest(root, k) == kth_by_size(root, k) == sorted(vals)[k - 1]
    print("all tests passed")

Early-exit iterative inorder and a size-augmented query, both checked against sorted values on random BSTs.

Complexity

Time: O(h + k) inorder; O(h) with subtree sizes. Space: O(h). Keeping sizes costs O(h) per update; balancing keeps h at O(log n).

By level

Fresher: Uses inorder to list values in order and stops at the k-th one. Explains why inorder of a BST is sorted.

Mid: Writes the early-exit iterative version and the size-augmented walk, and explains the update cost. Handles k out of range.

Senior: Discusses order-statistic trees in production libraries, B-trees with counts for on-disk rank queries, and the trade-off between maintaining counts on writes versus scanning on reads. Picks the approach from the measured read to write ratio.

Key points

  • Inorder of a BST is ascending
  • Stop as soon as k nodes are popped
  • Subtree sizes turn the query into a single root-to-leaf walk
  • Sizes must be updated on insert and delete
  • Balanced trees keep h logarithmic

Common mistakes

  • Collecting the whole inorder list when early exit is possible
  • Off-by-one with 1-indexed k
  • Forgetting to update sizes on deletion
  • Claiming O(log n) without a balanced tree

Follow-ups

  • How do you find the k-th largest instead?
  • How would you support rank(x), the number of values below x?
  • What if the tree is too large for memory and lives on disk?

Tips

  • Mention O(h + k), not O(n), for early exit
  • Bring up subtree sizes for the follow-up
  • Say what keeps h small

Evaluation rubric

  • Correct early-exit traversal
  • Correct augmented query
  • Discusses update cost
  • Correct complexity in terms of h
59.algorithms-0059Mediummid

Path sum on a binary tree: count the downward paths whose values add up to a target, where a path can start and end at any node.

Track the running sum from the root to the current node and a hash map of how many times each prefix sum occurs on the current root-to-node path. A path ending here sums to the target when running minus target appeared earlier on the path. Add the current sum, recurse, then remove it when backtracking. This is O(n) time against the O(n * h) brute force.

Full answer

Problem

Given the root of a binary tree and an integer target, return the number of paths whose node values sum to target. A path must go downward (parent to child) but may start and end at any node.

Example: for the tree 10 -> (5 -> (3 -> 3, -2), (2 -> -, 1)), (-3 -> -, 11) and target 8 the answer is 3: 5 + 3, 5 + 2 + 1 and -3 + 11.

Constraints: up to 1,000 nodes; values from -10^9 to 10^9 (negatives allowed, so pruning by sign is not possible).

Warm-up: "is there a root-to-leaf path with sum target" is a plain DFS that subtracts each value and checks at leaves.

Brute force

From every node, start a DFS downward and count paths reaching the target. Each start costs O(subtree size), giving O(n * h): O(n log n) balanced, O(n^2) on a chain.

Optimal approach

Prefix sums on the root-to-node path:

  1. seen = {0: 1} (the empty prefix, so paths starting at the root count).
  2. At a node, running += node.val. Paths ending here: seen[running - target].
  3. Increment seen[running], recurse into both children, then decrement it before returning.

Why it works

The sum of the downward path from ancestor a (exclusive) to the current node equals running - prefix(a). That equals target exactly when prefix(a) = running - target, so the count of such ancestors is a hash lookup. Removing the current prefix on the way back keeps the map limited to the current root-to-node path, so prefixes from other branches never pair with this node.

Complexity

O(n) time with O(1) average hash operations. O(h) space for recursion and the map.

Code

python
import random
from collections import defaultdict


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def has_path_sum(root, target):
    """Root-to-leaf path summing to target (the warm-up)."""
    if root is None:
        return False
    if root.left is None and root.right is None:
        return root.val == target
    rest = target - root.val
    return has_path_sum(root.left, rest) or has_path_sum(root.right, rest)


def count_paths(root, target):
    """Downward paths (any start, any end) summing to target. Prefix sums: O(n)."""
    seen = defaultdict(int)
    seen[0] = 1                          # empty prefix, so paths starting at the root count

    def walk(node, running):
        if node is None:
            return 0
        running += node.val
        found = seen[running - target]   # earlier prefixes that leave exactly target
        seen[running] += 1
        found += walk(node.left, running) + walk(node.right, running)
        seen[running] -= 1               # backtrack: leave this root-to-node path
        return found
    return walk(root, 0)


def brute(root, target):
    """O(n * h): start a downward walk from every node."""
    def from_node(n, rem):
        if n is None:
            return 0
        rem -= n.val
        return (rem == 0) + from_node(n.left, rem) + from_node(n.right, rem)

    def every(n):
        return 0 if n is None else from_node(n, target) + every(n.left) + every(n.right)
    return every(root)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.25:
        return None
    return TreeNode(rng.randint(-3, 3), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(10, TreeNode(5, TreeNode(3, TreeNode(3), TreeNode(-2)), TreeNode(2, None, TreeNode(1))),
                 TreeNode(-3, None, TreeNode(11)))
    assert count_paths(t, 8) == 3                   # 5+3, 5+2+1, -3+11
    assert has_path_sum(t, 18) and not has_path_sum(t, 100)   # 10+5+3 is not a leaf path; 10+5+2+1 = 18
    assert count_paths(None, 0) == 0
    rng = random.Random(59)
    for _ in range(2000):
        r = random_tree(rng, 5)
        k = rng.randint(-4, 4)
        assert count_paths(r, k) == brute(r, k)
    print("all tests passed")

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

Edge cases

Empty tree (0). Target 0 with zero-valued nodes (single nodes count as paths). Negative values. Several equal prefix sums on one path (the counter, not a set, matters).

Pattern

This is the "subarray sum equals k" prefix-sum trick moved onto a tree, with backtracking to keep the state path-local. The same combination solves "longest path with a given XOR" and counting paths under modular constraints.

python
import random
from collections import defaultdict


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def has_path_sum(root, target):
    """Root-to-leaf path summing to target (the warm-up)."""
    if root is None:
        return False
    if root.left is None and root.right is None:
        return root.val == target
    rest = target - root.val
    return has_path_sum(root.left, rest) or has_path_sum(root.right, rest)


def count_paths(root, target):
    """Downward paths (any start, any end) summing to target. Prefix sums: O(n)."""
    seen = defaultdict(int)
    seen[0] = 1                          # empty prefix, so paths starting at the root count

    def walk(node, running):
        if node is None:
            return 0
        running += node.val
        found = seen[running - target]   # earlier prefixes that leave exactly target
        seen[running] += 1
        found += walk(node.left, running) + walk(node.right, running)
        seen[running] -= 1               # backtrack: leave this root-to-node path
        return found
    return walk(root, 0)


def brute(root, target):
    """O(n * h): start a downward walk from every node."""
    def from_node(n, rem):
        if n is None:
            return 0
        rem -= n.val
        return (rem == 0) + from_node(n.left, rem) + from_node(n.right, rem)

    def every(n):
        return 0 if n is None else from_node(n, target) + every(n.left) + every(n.right)
    return every(root)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.25:
        return None
    return TreeNode(rng.randint(-3, 3), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(10, TreeNode(5, TreeNode(3, TreeNode(3), TreeNode(-2)), TreeNode(2, None, TreeNode(1))),
                 TreeNode(-3, None, TreeNode(11)))
    assert count_paths(t, 8) == 3                   # 5+3, 5+2+1, -3+11
    assert has_path_sum(t, 18) and not has_path_sum(t, 100)   # 10+5+3 is not a leaf path; 10+5+2+1 = 18
    assert count_paths(None, 0) == 0
    rng = random.Random(59)
    for _ in range(2000):
        r = random_tree(rng, 5)
        k = rng.randint(-4, 4)
        assert count_paths(r, k) == brute(r, k)
    print("all tests passed")

Root-to-leaf warm-up, prefix-sum counter with backtracking, and an O(n * h) brute force cross-check on random trees with negatives.

Complexity

Time: O(n) average. Space: O(h). Hash-map operations are average O(1); the brute force is O(n * h).

By level

Fresher: Solves the root-to-leaf warm-up and the O(n * h) count from every node, explaining the cost. Follows the prefix-sum idea when shown the array version.

Mid: Writes the prefix-sum DFS with the seed and backtracking, and explains why order of lookup and insert matters. States O(n) average time.

Senior: Generalizes path-local state with backtracking to other tree aggregates and explains when a global map would give wrong answers. Discusses iterative implementations and integer overflow in languages with fixed-width types.

Key points

  • Path sum = running - prefix of an ancestor
  • Seed the map with {0: 1}
  • Look up before inserting the current prefix
  • Decrement when backtracking
  • Negatives rule out early pruning

Common mistakes

  • Forgetting the {0: 1} seed so paths from the root are missed
  • Inserting the current prefix before the lookup, which counts empty paths when target is 0
  • Not removing the prefix on return, so other branches leak in
  • Using a set instead of counts

Follow-ups

  • How would you return the paths themselves?
  • What if paths can go up and then down (any two nodes)?
  • How does the array version (subarray sum equals k) relate?

Tips

  • Point out the link to the array problem
  • Explain the backtracking step clearly
  • Test with target 0

Evaluation rubric

  • Correct prefix-sum logic
  • Correct backtracking
  • Handles negatives and target 0
  • Correct complexity
60.algorithms-0060Mediummid

Implement a trie (prefix tree) with insert, search and starts-with, then extend it to count words with a prefix and return autocomplete suggestions.

Each trie node maps a character to a child and has an end flag. Insert walks or creates one node per character and marks the end; search walks and checks the end flag; starts-with only checks that the walk succeeds. All are O(L) for a word of length L. A pass-through counter on each node answers prefix counts in O(L), and a DFS below the prefix node lists suggestions.

Full answer

Problem

Implement Trie with insert(word), search(word) (exact match) and starts_with(prefix). Then add count_prefix(prefix) and words_with_prefix(prefix, limit) for autocomplete.

Example: after inserting apple, app, apply, bat, bath, search("app") is True, search("ap") is False, starts_with("ap") is True, count_prefix("app") is 3, and suggestions for app are ["app", "apple", "apply"].

Constraints: up to 3 * 10^4 operations, words of length 1 to 2,000, lowercase letters.

Brute force

Keep a list (or set) of words. Exact search is O(1) with a set, but starts-with and prefix counting scan every word: O(N * L) per query.

A sorted list with binary search answers prefix queries in O(L log N) but costs O(N) per insert.

Optimal approach

A tree of nodes, each with children: dict[char, node], end: bool and count: int (words passing through).

  • insert: walk from the root, creating missing children, incrementing count; mark end at the last node. Skip if the word already exists so counts stay correct.
  • search: walk; return end of the final node, or False if a child is missing.
  • starts_with: walk; True if every character exists.
  • words_with_prefix: walk to the prefix node, then DFS in sorted child order, collecting words until the limit.

Why it works

All words sharing a prefix share the same path from the root, so the node reached by a prefix represents exactly the set of words with that prefix. The end flag separates "app is a word" from "app is only a prefix of apple". The pass-through count at a node equals the number of distinct inserted words below it.

Complexity

insert, search, starts_with, count_prefix: O(L). Suggestions: O(L + size of the explored subtree). Space: O(total characters inserted) nodes in the worst case, less when prefixes are shared.

Code

python
import random


class TrieNode:
    __slots__ = ("children", "end", "count")

    def __init__(self):
        self.children = {}
        self.end = False                 # a word ends here
        self.count = 0                   # words passing through here (for prefix counts)


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        if self.search(word):
            return                       # keep counts correct on duplicate inserts
        node = self.root
        node.count += 1
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
            node.count += 1
        node.end = True

    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return bool(node and node.end)

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

    def count_prefix(self, prefix):
        node = self._walk(prefix)
        return node.count if node else 0

    def words_with_prefix(self, prefix, limit=10):
        """Autocomplete: DFS in sorted order below the prefix node."""
        node, out = self._walk(prefix), []
        if node is None:
            return out
        stack = [(node, prefix)]
        while stack and len(out) < limit:
            n, s = stack.pop()
            if n.end:
                out.append(s)
            for ch in sorted(n.children, reverse=True):
                stack.append((n.children[ch], s + ch))
        return out


if __name__ == "__main__":
    t = Trie()
    for w in ("apple", "app", "apply", "bat", "bath"):
        t.insert(w)
    t.insert("app")
    assert t.search("app") and t.search("apple") and not t.search("ap")
    assert t.starts_with("ap") and not t.starts_with("c")
    assert t.count_prefix("app") == 3 and t.count_prefix("ba") == 2 and t.count_prefix("") == 5
    assert t.words_with_prefix("app") == ["app", "apple", "apply"]
    assert t.words_with_prefix("z") == []
    rng = random.Random(60)
    words = {"".join(rng.choice("abc") for _ in range(rng.randint(1, 5))) for _ in range(200)}
    t2 = Trie()
    for w in words:
        t2.insert(w)
    for _ in range(500):
        q = "".join(rng.choice("abc") for _ in range(rng.randint(0, 5)))
        assert t2.search(q) == (q in words)
        assert t2.count_prefix(q) == sum(w.startswith(q) for w in words)
    print("all tests passed")

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

Edge cases

Duplicate inserts (do not double-count). Empty prefix (matches every word). A word that is a prefix of another (app and apple). Very long words. Deletion needs decrementing counts and pruning empty nodes.

Pattern

Prefix tree for shared-prefix queries. Tries power autocomplete, word search on a board (prune DFS by prefix), IP routing tables (longest prefix match on bits), and the maximum XOR pair problem with a binary trie.

python
import random


class TrieNode:
    __slots__ = ("children", "end", "count")

    def __init__(self):
        self.children = {}
        self.end = False                 # a word ends here
        self.count = 0                   # words passing through here (for prefix counts)


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        if self.search(word):
            return                       # keep counts correct on duplicate inserts
        node = self.root
        node.count += 1
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
            node.count += 1
        node.end = True

    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return bool(node and node.end)

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

    def count_prefix(self, prefix):
        node = self._walk(prefix)
        return node.count if node else 0

    def words_with_prefix(self, prefix, limit=10):
        """Autocomplete: DFS in sorted order below the prefix node."""
        node, out = self._walk(prefix), []
        if node is None:
            return out
        stack = [(node, prefix)]
        while stack and len(out) < limit:
            n, s = stack.pop()
            if n.end:
                out.append(s)
            for ch in sorted(n.children, reverse=True):
                stack.append((n.children[ch], s + ch))
        return out


if __name__ == "__main__":
    t = Trie()
    for w in ("apple", "app", "apply", "bat", "bath"):
        t.insert(w)
    t.insert("app")
    assert t.search("app") and t.search("apple") and not t.search("ap")
    assert t.starts_with("ap") and not t.starts_with("c")
    assert t.count_prefix("app") == 3 and t.count_prefix("ba") == 2 and t.count_prefix("") == 5
    assert t.words_with_prefix("app") == ["app", "apple", "apply"]
    assert t.words_with_prefix("z") == []
    rng = random.Random(60)
    words = {"".join(rng.choice("abc") for _ in range(rng.randint(1, 5))) for _ in range(200)}
    t2 = Trie()
    for w in words:
        t2.insert(w)
    for _ in range(500):
        q = "".join(rng.choice("abc") for _ in range(rng.randint(0, 5)))
        assert t2.search(q) == (q in words)
        assert t2.count_prefix(q) == sum(w.startswith(q) for w in words)
    print("all tests passed")

Dict-based trie with end flags, pass-through counts and sorted autocomplete; random words are checked against a set and a startswith count.

Complexity

Time: O(L) per operation. Space: O(total characters). A fixed 26-slot array per node is faster in some languages but uses more memory for sparse alphabets.

By level

Fresher: Implements insert, search and starts_with with a dict per node and explains the end flag with an example. States O(L) per operation.

Mid: Adds prefix counts and autocomplete, handles duplicate inserts, and discusses array versus dict children. Implements delete with pruning.

Senior: Discusses radix trees, top-k suggestions cached at nodes, ranking by frequency, and memory limits for millions of words. Compares a trie with a sorted array plus binary search for read-heavy workloads.

Key points

  • Node = children map + end flag
  • Shared prefixes share one path
  • search checks end, starts_with does not
  • Pass-through counts answer prefix counts in O(L)
  • Autocomplete = walk to prefix node then DFS

Common mistakes

  • Returning True from search for a prefix that is not a full word
  • Double-counting duplicate inserts
  • Allocating 26-element arrays for a huge Unicode alphabet
  • Deleting nodes still used by other words

Follow-ups

  • How would you implement delete?
  • How would you rank suggestions by popularity?
  • How do you reduce memory (compressed trie, radix tree)?

Tips

  • Define the node fields first
  • Show the difference between search and starts_with with app and apple
  • Mention memory trade-offs

Evaluation rubric

  • Correct insert, search, starts_with
  • Correct prefix counts
  • Working autocomplete
  • Discusses memory