Algorithmic Problem-Solving and Data Structure Selection Questions
The higher-order meta-skill of attacking an unfamiliar problem: recognizing problem archetypes and mapping them to known techniques, decomposing under constraints, and choosing, composing, or designing the right data structures to meet specified operation costs (LRU cache, min-stack, ordered maps, disjoint-set/union-find). Covers reasoning about trade-offs between competing structures and approaches, working through medium-to-hard problems methodically, handling problem variations, and communicating an approach before coding. The connective-tissue topic that ties the individual structure and algorithm topics together, rather than any single structure or algorithm.
You need the shortest path in a weighted graph. Walk through how you would choose between BFS, Dijkstra, Bellman-Ford, and A*, based on whether edges are weighted, whether negative weights are possible, and whether you need single-source or all-pairs distances. When would A*'s heuristic actually help over plain Dijkstra, and what property must that heuristic have?
Sample Answer
Direct answer
Pick based on two properties of the graph and one property of the query: if every edge has the same weight, breadth-first search (BFS) alone gives shortest paths in linear time; if weights differ but are never negative, Dijkstra's algorithm is the standard single-source choice; if a negative weight is possible (but no negative cycle), Dijkstra can give a wrong answer and Bellman-Ford is required instead; and if you need distances between every pair rather than from one source, Floyd-Warshall (a dynamic-programming algorithm that considers every node in turn as a possible shortcut between every pair) is the natural fit for all-pairs, or equivalently running Dijkstra from every node. A* only changes single-source, non-negative-weight search: it adds a heuristic estimate of remaining distance to prioritize expansion toward a specific goal, and it only helps, versus plain Dijkstra, when that heuristic is admissible (it never overestimates the true remaining cost), since an inadmissible heuristic can cause A* to return a path that is not actually shortest.
Structured elaboration
Decision order:
- Are all edge weights equal (or is the graph unweighted)? Use BFS: O(V+E), no priority queue needed at all.
- Do you need distances between every pair of nodes, not just from one source? Use Floyd-Warshall, O(V3), or repeat Dijkstra from every source if the graph is sparse and there are no negative weights.
- Otherwise, single-source with weights: are negative edge weights possible? If yes, use Bellman-Ford, O(V⋅E), which also detects a negative cycle if one exists (a cycle whose total weight is negative, which makes "shortest path" undefined, since you could loop it forever to keep decreasing the cost). If no, use Dijkstra, O((V+E)logV) with a binary heap.
- If you additionally have a single, known goal node (not "distances to everywhere"), and a decent estimate of remaining distance, layer A* on top of Dijkstra's non-negative-weight assumption to reduce how much of the graph gets explored.
Why Dijkstra breaks under negative weights: once Dijkstra pops a node off its priority queue, it treats that node's distance as final and never revisits it, on the assumption that nothing already queued could possibly offer a shorter path, since all remaining edges only add non-negative weight. A negative edge violates that assumption directly: a longer-looking path discovered later can still turn out shorter once a negative edge is added to it.
What A's heuristic must guarantee*: admissibility, never overestimating the true remaining cost to the goal. Given an admissible heuristic, A* is guaranteed to still find a shortest path, exactly like Dijkstra, but it explores fewer nodes when the heuristic is informative, because it prioritizes nodes that look closer to the goal rather than merely closer to the start. (A stronger property, consistency, additionally guarantees a node is never re-expanded after being finalized, which is what lets A* implementations skip the "revisit and relax an already-closed node" bookkeeping that a merely admissible-but-inconsistent heuristic would otherwise require.) A straight-line (Euclidean) distance heuristic on a road network or grid is a classic admissible choice, since no real route can be shorter than the straight line.
Worked example
Bellman-Ford correctness under a negative edge, where Dijkstra gets it wrong:
import math
def dijkstra(adj, src):
import heapq
dist = {src: 0}
finalized = set()
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if u in finalized:
continue
finalized.add(u)
for v, w in adj.get(u, []):
if v in finalized:
continue
nd = d + w
if nd < dist.get(v, math.inf):
dist[v] = nd
heapq.heappush(pq, (nd, v))
return dist
def bellman_ford(edges, nodes, src):
dist = {n: math.inf for n in nodes}
dist[src] = 0
for _ in range(len(nodes) - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError("negative cycle detected")
return dist
# True shortest A->B is via C: 1 -> 4 + (-10) = -6, but Dijkstra finalizes
# B at distance 1 (direct edge) before C is even processed.
adj = {"A": [("B", 1), ("C", 4)], "C": [("B", -10)]}
edges = [("A", "B", 1), ("A", "C", 4), ("C", "B", -10)]
nodes = ["A", "B", "C"]
print("dijkstra:", dijkstra(adj, "A"))
print("bellman_ford:", bellman_ford(edges, nodes, "A"))
Running this prints:
dijkstra: {'A': 0, 'B': 1, 'C': 4}
bellman_ford: {'A': 0, 'B': -6, 'C': 4}
Dijkstra reports B at distance 1 (wrong: it finalized B via the direct edge before discovering the cheaper route through C), while Bellman-Ford correctly finds -6 via A to C to B.
A exploring fewer nodes than Dijkstra given an admissible heuristic*, on an open 20x20 grid from (0,0) to (5,5), using Manhattan distance as the heuristic:
import heapq
def neighbors(pos, size):
x, y = pos
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < size and 0 <= ny < size:
yield (nx, ny)
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def search(start, goal, size, use_heuristic):
h = (lambda n: manhattan(n, goal)) if use_heuristic else (lambda n: 0)
g = {start: 0}
pq = [(h(start), start)]
visited = set()
expansions = 0
while pq:
_, node = heapq.heappop(pq)
if node in visited:
continue
visited.add(node)
expansions += 1
if node == goal:
break
for nb in neighbors(node, size):
ng = g[node] + 1
if ng < g.get(nb, float("inf")):
g[nb] = ng
heapq.heappush(pq, (ng + h(nb), nb))
return g[goal], expansions
size = 20
start, goal = (0, 0), (5, 5)
dist_astar, exp_astar = search(start, goal, size, use_heuristic=True)
dist_dij, exp_dij = search(start, goal, size, use_heuristic=False)
print("A* distance:", dist_astar, "nodes expanded:", exp_astar)
print("Dijkstra distance:", dist_dij, "nodes expanded:", exp_dij)
Running this prints:
A* distance: 10 nodes expanded: 36
Dijkstra distance: 10 nodes expanded: 61
Both find the same correct shortest distance (10), but A* reaches it having expanded 36 nodes against Dijkstra's 61, because the heuristic steered expansion toward the goal instead of outward in every direction equally.
Trade-offs & pitfalls
A common mistake is treating A* as "a different algorithm" from Dijkstra rather than as Dijkstra with a heuristic added to the priority; with a heuristic of zero everywhere (as in the comparison above), A* degenerates to exactly Dijkstra, which is a good way to check an A* implementation for bugs. A second pitfall is picking a heuristic that overestimates in some region "because it prunes more nodes": an inadmissible heuristic can make A* return a path that is not actually shortest, so any heuristic must be checked against the admissibility property, not just judged by how much it speeds things up. Practically, Dijkstra's own implementation constant matters too: with a binary heap, each edge relaxation that improves a distance costs O(logV) to sift, which under many decrease-key-style relaxations is the dominant cost; the common fix is not switching to a Fibonacci or pairing heap (both have amortized O(1) or near-O(1) decrease-key but carry higher constant factors and more complex implementations) but instead allowing duplicate, stale entries in a plain binary heap and lazily discarding them on pop, which is what the Dijkstra implementation above already does and is the standard practical choice.
What does it mean for a sorting algorithm to be stable, and why does that matter when you are sorting by a secondary key after already having sorted by a primary one? Name a stable and an unstable sort and say what would break if you used the unstable one in a multi-key sort.
Sample Answer
Direct answer
A sorting algorithm is stable if it preserves the relative order of elements
that compare equal on the sort key. If two records tie on the key you sorted
by, a stable algorithm guarantees the one that came first in the input still
comes first in the output. This matters for multi-key sorts: if you sort by a
secondary key after already sorting by a primary one, stability is what lets
the primary ordering survive as a tiebreaker inside each secondary-key group.
Merge sort and Python's Timsort (the algorithm behind sorted() and list.sort())
are stable; classic in-place selection sort and a typical quicksort are not.
Structured elaboration
Why stability matters for multi-key sorts. The standard trick for sorting
by (primary key, secondary key) without writing a composite comparator is:
sort once by the primary key, then sort the result by the secondary key. This
only produces the correct combined order if the second sort is stable: a
stable sort only reorders elements that actually differ on the secondary key,
so within any group of equal secondary-key values, the primary-key order from
step one is left untouched. An unstable sort makes no such promise: it may
reorder equal-secondary-key elements arbitrarily while grouping them, silently
destroying the primary ordering you already paid to establish.
A stable sort: merge sort, and Timsort (the hybrid merge/insertion sort
used by Python and Java's Collections.sort for objects). Both work by
merging or shifting elements without ever swapping two elements past an equal
one, so ties keep their input order.
An unstable sort: classic in-place selection sort (repeatedly swap the
current position with the position of the next-smallest remaining element).
The swap step moves elements across long distances in the array, including
past other elements with the same key, which is exactly what breaks ties.
Typical in-place quicksort implementations are unstable for the same reason
(the partition step swaps non-adjacent elements).
If you only have an unstable sort available, you can force stability by
attaching the original index to each record and sorting by (key, original_index)
instead of key alone. Ties on key are then broken by index, which exactly
reproduces stable behavior, at the cost of allocating one extra field per record.
Worked example
Take four employee records, already sorted by name (the primary key):
| dept | name |
|---|---|
| Sales | Alvarez |
| Eng | Chen |
| Sales | Diallo |
| Eng | Ito |
Now sort by department (the secondary key). A stable sort must produce:
Eng: Chen, Ito (name order preserved)
Sales: Alvarez, Diallo (name order preserved)
Running this in Python, where sorted() is stable, versus a hand-rolled
unstable selection sort, on the exact same input:
records = [
{"name": "Alvarez", "dept": "Sales"},
{"name": "Chen", "dept": "Eng"},
{"name": "Diallo", "dept": "Sales"},
{"name": "Ito", "dept": "Eng"},
]
stable_result = sorted(records, key=lambda r: r["dept"])
def unstable_selection_sort_by_dept(items):
items = list(items)
n = len(items)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if items[j]["dept"] < items[min_idx]["dept"]:
min_idx = j
items[i], items[min_idx] = items[min_idx], items[i]
return items
unstable_result = unstable_selection_sort_by_dept(records)
print([(r["dept"], r["name"]) for r in stable_result])
print([(r["dept"], r["name"]) for r in unstable_result])
Output (verified by running this exact code):
[('Eng', 'Chen'), ('Eng', 'Ito'), ('Sales', 'Alvarez'), ('Sales', 'Diallo')]
[('Eng', 'Chen'), ('Eng', 'Ito'), ('Sales', 'Diallo'), ('Sales', 'Alvarez')]
The Eng group comes out identical either way, but the Sales group is
reversed under the unstable sort: Diallo now precedes Alvarez, even though
Alvarez came first alphabetically. That reversal is the bug: any downstream
code relying on "same department, alphabetical order" is now silently wrong,
and the failure is data-dependent, so it will not show up on every input.
Trade-offs & pitfalls
- Stability is a property of the algorithm's specification, not just a given
implementation detail: "quicksort" is not stable by definition, but a
particular library's sort might document stability as a guarantee (check
the docs rather than assuming from the algorithm's name). - The index-as-tiebreaker trick works with any comparison sort, stable or not,
but costs O(n) extra memory for the index field and slightly more comparison
overhead per element; it is the right choice when the language's built-in
sort is unstable by contract (e.g. a raw quicksort library call) and you
cannot swap in a stable one. - A common wrong turn is assuming "the final order looks right on my test
data" is proof of stability; instability is a tie-breaking behavior that
only shows up when there are actual ties, so it hides in datasets with few
duplicate keys and surfaces later at a different data distribution. - Do not confuse stability with sort correctness on the primary sort key
itself: an unstable sort still produces a fully correct order on the key it
was told to sort by, it only fails to preserve unrelated prior ordering
among equal elements.
Extend the eviction policy so the cache tracks how often each key is used, not just how recently: get(key) and put(key, value) must both stay O(1), and when the cache is full it evicts the least-frequently-used entry, breaking ties by least-recently-used. Describe the structures that keep both the frequency count and the recency-within-a-frequency ordering O(1) to update.
Sample Answer
Direct answer
Keep a hash map from key to a node holding the value and a frequency count, and a separate doubly linked list (a list where each node points to both its neighbors, so removal and insertion at any known node are O(1), no shifting required) per frequency value. Eviction always pops from the lowest-frequency list, and within that list the head is the least-recently-used (LRU) entry, so the head is exactly the least-frequently-used (LFU) entry with ties broken by recency. Tracking the current minimum frequency separately means you never have to scan for the lowest bucket.
Structured elaboration
Three pieces of state:
key_node: hash map from key to its node (value, frequency).freq_lists: hash map from frequency to a doubly linked list of nodes at that frequency, ordered by recency (oldest at the head, newest at the tail).min_freq: the smallest frequency that currently has at least one entry.
On get(key) (and on put for an existing key): look up the node in O(1) via key_node, remove it from its current frequency's list, increment its frequency, and append it to the new frequency's list (append means "just used," so it goes to the tail, the recent end). If removing it emptied the old list and that old frequency was min_freq, bump min_freq by one, since a bucket can only ever empty at the current minimum (nothing decreases frequency).
On put(key, value) for a new key at full capacity: evict the head of freq_lists[min_freq] (LFU, LRU tie-break), remove it from key_node, then insert the new key at frequency 1 and reset min_freq to 1 (a brand new key is always tied for lowest).
Every step touches only hash map entries and linked-list splices at already-known nodes, so both operations run in O(1) average time.
Worked example
class _Node:
__slots__ = ("key", "value", "freq", "prev", "next")
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.freq = 1
self.prev = None
self.next = None
class _FreqList:
"""Doubly linked list of nodes sharing one frequency, ordered by
recency (head = least recently used within this frequency)."""
def __init__(self):
self.head = _Node()
self.tail = _Node()
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def append(self, node):
node.prev = self.tail.prev
node.next = self.tail
node.prev.next = node
self.tail.prev = node
self.size += 1
def remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
self.size -= 1
def pop_lru(self):
node = self.head.next
self.remove(node)
return node
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.min_freq = 0
self.key_node: dict[int, _Node] = {}
self.freq_lists: dict[int, _FreqList] = {}
def _bump(self, node):
old_freq = node.freq
self.freq_lists[old_freq].remove(node)
if self.freq_lists[old_freq].size == 0:
del self.freq_lists[old_freq]
if self.min_freq == old_freq:
self.min_freq += 1
node.freq += 1
self.freq_lists.setdefault(node.freq, _FreqList()).append(node)
def get(self, key: int) -> int:
if key not in self.key_node:
return -1
node = self.key_node[key]
self._bump(node)
return node.value
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key in self.key_node:
node = self.key_node[key]
node.value = value
self._bump(node)
return
if self.size == self.capacity:
evict = self.freq_lists[self.min_freq].pop_lru()
del self.key_node[evict.key]
if self.freq_lists[self.min_freq].size == 0:
del self.freq_lists[self.min_freq]
self.size -= 1
node = _Node(key, value)
self.key_node[key] = node
self.freq_lists.setdefault(1, _FreqList()).append(node)
self.min_freq = 1
self.size += 1
cache = LFUCache(2)
cache.put(1, 1)
cache.put(2, 2)
print(cache.get(1)) # 1, freq(1) becomes 2
cache.put(3, 3) # capacity full; key 2 is the only entry at min_freq=1, evicted
print(cache.get(2)) # -1, evicted
print(cache.get(3)) # 3, freq(3) becomes 2
cache.put(4, 4) # freq-1 bucket is empty so min_freq=2; key 1 is LRU there, evicted
print(cache.get(1)) # -1, evicted
print(cache.get(3)) # 3
print(cache.get(4)) # 4
Running this prints, in order:
1
-1
3
-1
3
4
Key points
- Each frequency bucket is itself an LRU list, which is what makes the tie-break automatic: the head is always the oldest entry at that frequency.
min_freqonly ever needs to increase, and only when the bucket it points at empties out, so tracking it costs O(1) instead of scanning.
Complexity
O(1) average per get/put O(capacity)for space (one node per stored key, plus the bucket lists which partition those same nodes).
Edge cases
capacity == 0:putis a no-op,getalways returns -1.- Repeated
puton an existing key must bump frequency the same waygetdoes (shown above), not just overwrite the value. - A
putthat overwrites a key that would otherwise trigger eviction must update, not evict, since the key is already present.
Trade-offs & pitfalls
The classic bug is forgetting to advance min_freq when the bucket it points at becomes empty. It's tempting to just track the smallest key of freq_lists, but that requires a scan; keeping min_freq as its own O(1)-updated variable is what preserves the overall bound. In Python, a bucket can be implemented as an OrderedDict instead of a hand-rolled doubly linked list (using move_to_end and popitem(last=False)), trading a little control for much less code; for an interview, either is acceptable as long as you can name why it's still O(1). Also worth naming as depth beyond what most interviews require: an LFU cache is more complex to build and reason about than a plain LRU cache, so in practice teams only reach for LFU when access patterns are genuinely skewed by frequency rather than recency, and even then often prefer an approximate LFU (a lossy frequency sketch) over an exact one to bound memory growth.
A candidate (or a teammate) has written a memoized recursive solution to a combinatorial problem, but it still times out or the code has spiraled in complexity. Walk through how you would diagnose whether the issue is a missing memoization key, an avoidable exponential branching factor, or a case where the technique itself (recursion) is the wrong fit, and how you would coach someone through fixing it.
Sample Answer
Direct answer
Three distinct root causes produce the same symptom ("memoized recursion still too slow or too tangled"), and they call for different fixes: a missing memoization key means the cache conflates genuinely different subproblems and can silently produce wrong answers, not just slow ones; an avoidable exponential branching factor means the recursion's own choice structure revisits far more distinct states than the problem actually has, often because a natural ordering constraint (like a monotonically advancing index) was dropped; and a technique mismatch means the true, minimal state space is itself exponential (or the recursive decomposition does not actually shrink the problem), so no amount of caching helps. Diagnosing which one is happening starts with checking whether the function's declared arguments actually determine its answer uniquely.
Structured elaboration
Diagnostic order
- Is the memo key complete? Ask: given only the arguments used as the memo key, could two genuinely different call sites ever need two different correct answers? If yes, the key is missing a dimension of state, and the bug is a correctness bug (wrong answers), not merely a performance one.
- Is the branching factor itself avoidable? With a correct key, count how many distinct memo keys actually get created relative to what the input bounds imply. If the recursion is generating states parameterized on something like "the exact subset chosen so far" when a much smaller signal (an index, a running total) would fully determine the future, the branching factor is inflated by the state design itself, not by an inherent property of the problem.
- Is recursion the wrong family entirely? If, even after fixing the state design, the number of truly distinct necessary states is still exponential in the input (or the desired output itself is exponential, such as enumerating every valid arrangement rather than counting or testing feasibility), no memoization strategy reduces the work below that inherent size. That is a sign to either accept the exponential cost as necessary (if literal enumeration is really required) or ask whether a different question (a count, or an existence check) is what is actually needed, which likely does have a compact recurrence.
Coaching flow once the category is known
- For a missing key: have the engineer write out, in one sentence, "two call sites with the same current memo key but different correct answers," and let them find the missing dimension themselves; this tends to make the bug obvious and self-taught rather than corrected for them.
- For an inflated branching factor: ask them to state the smallest set of numbers that fully determines the rest of the computation from this point forward, then compare that to what they are actually passing as arguments.
- For a technique mismatch: ask what the true size of the state space is, in terms of the input's own bounds, independent of how the recursion is currently written, if it is exponential no matter how the recursion is restructured, that is the signal to look for a different algorithm family.
Worked example
Consider counting the number of subsets of a list (chosen by position, not by value) that sum exactly to a target, a classic 0/1 subset-sum count.
# Ground truth via brute force over all subsets, for comparison only.
def brute_force(nums, target):
n = len(nums)
return sum(
1
for mask in range(1 << n)
if sum(nums[j] for j in range(n) if mask & (1 << j)) == target
)
# Variant A: missing memoization key (drops the position index, only keys on
# the remaining target). Two different positions reaching the same remaining
# value get treated as the same subproblem, which they are not.
def count_subsets_broken(nums, target):
calls = [0]
memo = {}
def rec(i, remaining):
calls[0] += 1
if remaining == 0:
return 1
if remaining < 0 or i == len(nums):
return 0
if remaining in memo:
return memo[remaining]
result = rec(i + 1, remaining - nums[i]) + rec(i + 1, remaining)
memo[remaining] = result
return result
return rec(0, target), calls[0]
# Variant B: the memo key is technically complete (a used-items bitmask plus
# remaining target), but the state design itself is exponential: a bitmask
# over n items has 2^n possible values, when a simple position index would
# have sufficed. It also silently changes the question being answered, into
# counting ordered selections rather than subsets, because every recursive
# call is allowed to choose from the full remaining pool instead of only the
# items after a fixed position.
def count_orderings_blowup(nums, target):
calls = [0]
def rec(remaining, used_mask):
calls[0] += 1
if remaining == 0:
return 1
if remaining < 0:
return 0
total = 0
for j in range(len(nums)):
if not (used_mask & (1 << j)):
total += rec(remaining - nums[j], used_mask | (1 << j))
return total
return rec(target, 0), calls[0]
# Variant C: restructured with a monotonically advancing position index in
# the key, which is both correct and polynomial in the number of distinct
# states (index, remaining).
def count_subsets_correct(nums, target):
from functools import lru_cache
calls = [0]
@lru_cache(maxsize=None)
def rec(i, remaining):
calls[0] += 1
if remaining == 0:
return 1
if remaining < 0 or i == len(nums):
return 0
return rec(i + 1, remaining - nums[i]) + rec(i + 1, remaining)
result = rec(0, target)
rec.cache_clear()
return result, calls[0]
nums = [3, 1, 4, 2, 2]
target = 6
truth = brute_force(nums, target)
a_result, a_calls = count_subsets_broken(nums, target)
b_result, b_calls = count_orderings_blowup(nums, target)
c_result, c_calls = count_subsets_correct(nums, target)
print("ground truth:", truth)
print("A (missing index in key):", a_result, "calls:", a_calls)
print("B (mask-keyed, unfixed order):", b_result, "calls:", b_calls)
print("C (index+remaining, restructured):", c_result, "calls:", c_calls)
import random
random.seed(0)
for size in (5, 10, 14):
test_nums = [random.randint(1, 9) for _ in range(size)]
test_target = sum(test_nums[:max(1, size // 2)])
_, calls_b = count_orderings_blowup(test_nums, test_target)
_, calls_c = count_subsets_correct(test_nums, test_target)
print(f"n={size}: mask-keyed calls={calls_b}, index-keyed calls={calls_c}")
This prints:
ground truth: 4
A (missing index in key): 6 calls: 35
B (mask-keyed, unfixed order): 16 calls: 80
C (index+remaining, restructured): 4 calls: 30
n=5: mask-keyed calls=86, index-keyed calls=34
n=10: mask-keyed calls=401141, index-keyed calls=227
n=14: mask-keyed calls=11476445, index-keyed calls=330
Variant A gives 6, not the true 4, a wrong answer, not just a slow one, because dropping the index from the key conflates subproblems that happen to share a remaining target but have different items still available. Variant B gives 16, also wrong (it is counting ordered arrangements, effectively over-counting each valid subset once per permutation of its elements), and its call count explodes from 86 at n=5 to over eleven million at n=14, purely from the bitmask state blowing up exponentially, while variant C's call count grows only from 34 to 330 over the same range, confirming the fix (a linear position index instead of an exponential mask) resolves both the correctness bug and the exponential blowup at once.
Trade-offs & pitfalls
It is tempting to treat "still slow after adding memoization" as automatically a branching-factor problem and reach for a bigger cache or more aggressive pruning; the data above shows that a state-design flaw can produce a wrong answer that also happens to be slow, and fixing only the speed (say, by adding memoization on top of variant B's bitmask key) would still return the wrong count, just faster. The genuinely hardest category to recognize is a real technique mismatch: if a problem's honestly-minimal state space is exponential (for example, truly enumerating every valid combination when the count of them is exponential), no clever memo key rescues it, and the coaching conversation needs to shift from "how do we memoize this correctly" to "does the caller actually need every arrangement enumerated, or would a count or feasibility check suffice.
Find the contiguous subarray with the largest sum in an array of integers (which may include negative numbers), in O(n) time and O(1) space. Explain the one-pass running-max idea (Kadane's algorithm), why it still works when every number is negative, and how you would adapt it to track the maximum product instead of the maximum sum.
Sample Answer
Direct answer
Kadane's algorithm makes one pass, keeping a running sum that resets whenever it would drop to zero or below (since a non-positive running sum can never help extend a future subarray), and tracks the best sum seen along the way. It still works when every number is negative because the running sum is initialized directly from the first element rather than from zero, so the algorithm falls back to reporting the single least-negative element rather than incorrectly returning an empty-subarray sum of 0. Adapting it to the maximum product instead of sum requires tracking a running minimum alongside the running maximum, since multiplying two negative numbers can turn the current running minimum into the new running maximum.
Structured elaboration
Why a single pass suffices (optimal substructure)
Let best(i) be the maximum sum of a subarray ending exactly at index i. Either that subarray is just the single element at i, or it extends the best subarray ending at i-1: best(i)=max(nums[i], best(i−1)+nums[i]). Because best(i) only depends on best(i−1), one forward pass that always keeps the running value non-negative (resetting to the current element whenever continuing the previous run would help less than starting fresh) computes every best(i) without ever revisiting earlier elements.
Why it still works for all-negative input
If every number is negative, a running sum that is allowed to reset to 0 whenever it goes non-positive would settle on 0 forever, which is wrong: there is no such thing as an empty subarray sum of 0 among the valid answers here, since a subarray must contain at least one element. Initializing the running sum from nums[0] (not from 0) and comparing against best_sum from the very first element sidesteps this: the algorithm naturally reports the largest (least negative) single element when nothing better exists.
Adapting to maximum product
Sum and product behave differently under a negative number: adding a negative always makes a running sum smaller, but multiplying by a negative flips the sign, so the smallest (most negative) running product can become the largest running product on the very next multiplication. The fix is to track both a running maximum and a running minimum product ending at the current index, and at each step consider all three candidates (the current element alone, the running max times the current element, and the running min times the current element) for both the new max and the new min.
Worked example
def max_subarray_sum(nums: list[int]) -> tuple[int, int, int]:
"""
Kadane's algorithm. O(n) time, O(1) extra space.
Returns (best_sum, start_index, end_index), inclusive.
"""
if not nums:
raise ValueError("nums must be non-empty")
best_sum = running_sum = nums[0]
best_l = best_r = run_start = 0
for i in range(1, len(nums)):
x = nums[i]
if running_sum <= 0:
running_sum = x
run_start = i
else:
running_sum += x
if running_sum > best_sum:
best_sum = running_sum
best_l, best_r = run_start, i
return best_sum, best_l, best_r
def max_subarray_product(nums: list[int]) -> int:
"""
Track running max AND running min, since multiplying by a negative
number can turn the running min into the new running max.
O(n) time, O(1) extra space.
"""
if not nums:
raise ValueError("nums must be non-empty")
best = curr_max = curr_min = nums[0]
for x in nums[1:]:
candidates = (x, curr_max * x, curr_min * x)
curr_max, curr_min = max(candidates), min(candidates)
best = max(best, curr_max)
return best
if __name__ == "__main__":
all_negative = [-3, -1, -4, -1, -5]
print("all-negative sum:", max_subarray_sum(all_negative))
mixed = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("mixed sum:", max_subarray_sum(mixed))
product_case = [2, 3, -2, 4]
print("product [2,3,-2,4]:", max_subarray_product(product_case))
product_flip = [-2, 3, -4]
print("product [-2,3,-4]:", max_subarray_product(product_flip))
Running this prints:
all-negative sum: (-1, 1, 1)
mixed sum: (6, 3, 6)
product [2,3,-2,4]: 6
product [-2,3,-4]: 24
For the all-negative array [-3,-1,-4,-1,-5], the best single element is -1 at index 1, matching the printed (-1, 1, 1). For the mixed array [-2,1,-3,4,-1,2,1,-5,4], the best subarray is indices 3 through 6 ([4,-1,2,1], summing to 6), matching the printed (6, 3, 6). For the product case [2,3,-2,4], the best product subarray is [2,3] giving 6; a full sweep including the trailing -2,4 would only give 2×3×(−2)×4=−48, confirming stopping at [2,3] is correct. For [-2,3,-4], the running-minimum trick matters directly: [-2] alone gives -2, [-2,3] gives -6, but the full array [-2,3,-4] gives (−2)×3×(−4)=24, the printed maximum, which only surfaces because the running minimum after [-2,3] (which is -6) gets multiplied by the next -4 and becomes the new running maximum.
Complexity
Time: O(n) for both the sum and the product version (a single pass). Space: O(1) extra for both.
Edge cases
- Empty input has no valid subarray; decide and state the desired behavior (raising, as here, is a reasonable default) rather than silently returning 0.
- A single-element array returns that element itself for both the sum and product versions.
- All-zero input for the product version needs the running max/min reset logic to correctly treat 0 as its own candidate, since 0 can be both the best local product (better than continuing a negative run) and a reset point.
- Very large products can overflow fixed-width integer types in languages that have them; Python's arbitrary-precision integers sidestep this, but it is worth naming as a real constraint in a language like C or Java.
Trade-offs & pitfalls
The most common wrong turn on the all-negative case is resetting the running sum to 0 whenever it goes negative rather than initializing from nums[0] and tracking the best sum from the start; that silently produces the wrong answer (0) instead of the correct least-negative single element. The most common wrong turn on the product adaptation is tracking only a running maximum, by direct analogy with the sum version, and missing that a running minimum is equally necessary because of how sign flips interact with multiplication. This family of one-pass running-state techniques is related to, but not identical to, two other fixed-window restatements sometimes asked alongside it: a fixed-window moving average keeps a single running sum, adding the newest element and subtracting the one that just fell out of the window, which is a simpler O(1)-per-step update than Kadane's since the window boundary is known in advance rather than discovered by a reset rule; a fixed-window moving maximum cannot get away with a single running maximum at all, because the current maximum can itself fall out of the window, so it needs a monotonic deque (a double-ended queue kept in decreasing order, so the front is always the window's current maximum) to know the next-best candidate the moment the old maximum expires. Naming that distinction (which of these needs one running value, and which needs a small ordered structure) is the difference between a correct and an incorrect answer to that folded variant, not just a stylistic choice.
Unlock Full Question Bank
Get access to all Algorithmic Problem-Solving and Data Structure Selection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.