Constant-Time LRU Cache and Unlimited-Reuse Combination Sum
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
This two-part problem pairs an in-memory data-structure design with a combinatorial search algorithm:
-
Part 1 — Constant-Time LRU Cache (
LRUCache): Design a fixed-capacity in-memory key-value store supportingget(key)andput(key, value)inO(1)average time. Whenever inserting a new key would exceed capacity, evict whichever stored key has gone unaccessed (by bothgetandput) for the longest time.- Show how pairing a hash table with a custom doubly linked list achieves
O(1)updates and evictions, and how permanent dummyheadandtailsentinel nodes eliminate null-pointer edge cases. - Explain why wrapping a standard library doubly linked list that hides its internal node objects (such as
java.util.LinkedList) drops back toO(n)updates, compare building from scratch against built-in access-ordered maps (LinkedHashMapin Java orOrderedDictin Python), and analyze time and space complexity.
- Show how pairing a hash table with a custom doubly linked list achieves
-
Part 2 — Unlimited-Reuse Target Sum (
combination_sum): Given a list of positive integer amountscandidatesand an integertarget, implementcombination_sum(candidates, target)to return all unique combinations of values chosen fromcandidateswhose sum equalstarget.- Any candidate value may be selected an unlimited number of times within a combination.
- Order within a combination does not distinguish two answers (
[3, 3, 4]and[3, 4, 3]represent the same combination). Format every returned combination in non-decreasing order, and return the list of combinations in ascending lexicographical order. - Explain your backtracking formulation, how sorting and index lower bounds prune unreachable branches and prevent duplicate permutations, how its time and space complexity scale, and why backtracking is preferable to bottom-up dynamic programming when enumerating every valid combination.
The automated judge evaluates combination_sum(candidates, target).
Examples
Example 1
Input: candidates = [3, 4, 7], target = 10
Output: [[3, 3, 4], [3, 7]]
Reusing 3 twice alongside 4 gives 3 + 3 + 4 = 10, and pairing 3 with 7 gives 3 + 7 = 10. No other multiset drawn from {3, 4, 7} sums to 10.
Example 2
Input: candidates = [3, 4, 6], target = 12
Output: [[3, 3, 3, 3], [3, 3, 6], [4, 4, 4], [6, 6]]
Four 3s (12), two 3s plus one 6 (12), three 4s (12), and two 6s (12) each hit target = 12. Each combination is non-decreasing and the four combinations appear in lexicographical order.
Example 3
Input: candidates = [4, 6], target = 5
Output: []
Every even combination formed from 4 and 6 is either 4 or at least 6, so 5 cannot be formed and an empty list is returned.
Constraints
0 <= len(candidates) <= 40- Every entry in
candidatesmust be a positive integer (amount >= 1; non-positive entries raiseValueError). candidatesis not guaranteed to be sorted and may contain repeated integers; repeated entries incandidatesmust not produce duplicate combinations in the output.- If
target < 0or no multiset sums totarget, return[].
Step-by-step walkthrough
Understand both parts of the interview prompt
This question combines two classic building blocks often paired in technical screens:
- Part 1 — In-memory LRU cache: Design a fixed-capacity key-value cache supporting
get(key)andput(key, value)inO(1)time. When inserting a brand-new key into a full cache, evict the Least Recently Used (LRU) entry — the one that has gone untouched by bothgetandputfor the longest time. - Part 2 — Target-sum combinations: Given positive transfer
candidatesand atargetamount, return every unique combination of candidates summing totarget, where each candidate may be reused any number of times. Order inside a combination does not distinguish answers ([3, 3, 4]and[3, 4, 3]are the same combination).
The automated judge tests Part 2 via
combination_sum(candidates, target). We will design and code bothLRUCacheandcombination_suminsolution.py, along with the Java/library comparisons and Dynamic Programming trade-offs asked in the prompt.- Part 1 — In-memory LRU cache: Design a fixed-capacity key-value cache supporting
Part 1 key idea: combine a hash map with a doubly linked list
Why can neither a hash map nor a linked list achieve
O(1)LRU alone? - A hash map (dict) finds any key inO(1)average time, but does not track which key was touched least recently without scanning. - A linked list keeps items ordered from most recent to least recent, but finding an arbitrary key inside the list takesO(n)linear scanning.We get
O(1)for everything by combining them: the dictionary mapskey -> CacheNode, jumping straight to the node inside a doubly linked list (a chain where each node stores bothprevandnextpointers so it can unlink itself inO(1)without searching from the head).To avoid messy
if node.prev is None:edge cases when the list is empty or has one element, we place two permanent dummy sentinel nodes (headandtail) at the ends:Dictionary (`self.nodes`): key 7 ------------------> [7: 70] key 4 -----> [4: 40] | | v Doubly linked list: [head] <===> [4: 40] <===> [7: 70] <===> [tail] dummy most recent least recent dummy (MRU) (LRU)Two details make this rock-solid: 1. Every real node sits strictly between
headandtail, sonode.prevandnode.nextare neverNone. Unlinking any node or inserting right afterheadalways updates the exact same four pointers. 2. EachCacheNodestores bothkeyandvalue. When the cache is full, we find the oldest node atself.tail.previnO(1), and readinglru_node.keytells us which entry to delete fromself.nodesinO(1).Code the LRU cache from scratch
Saving neighbor references into named variables (
prev_node,next_node,first_real) before rewiring pointers prevents accidental self-loops:from typing import Dict, Optional class CacheNode: """One node in the doubly linked recency list, storing both key and value.""" def __init__(self, key: int = 0, value: int = 0): # Storing `key` on the node lets us delete `nodes[oldest.key]` in O(1) on eviction. self.key = key self.value = value self.prev: Optional["CacheNode"] = None self.next: Optional["CacheNode"] = None class LRUCache: """In-memory LRU cache supporting O(1) average get(key) and put(key, value).""" def __init__(self, capacity: int): self.capacity = capacity # nodes: dict mapping key -> CacheNode for O(1) direct node lookup. self.nodes: Dict[int, CacheNode] = {} # Dummy sentinel nodes frame the list: # head <-> [most recently used] <-> ... <-> [least recently used] <-> tail self.head = CacheNode() self.tail = CacheNode() self.head.next = self.tail self.tail.prev = self.head def _unlink(self, node: CacheNode) -> None: """Bridge `node`'s neighbors directly to each other in O(1).""" prev_node = node.prev next_node = node.next assert prev_node is not None and next_node is not None prev_node.next = next_node next_node.prev = prev_node def _push_front(self, node: CacheNode) -> None: """Insert `node` right after dummy `head` (marking it most recently used) in O(1).""" first_real = self.head.next assert first_real is not None node.prev = self.head node.next = first_real self.head.next = node first_real.prev = node def get(self, key: int) -> int: node = self.nodes.get(key) if node is None: return -1 # Reading a key counts as a use, so move its node to the front. self._unlink(node) self._push_front(node) return node.value def put(self, key: int, value: int) -> None: if self.capacity <= 0: return # Case 1: Key already exists -> update value in place and refresh recency (no eviction). existing = self.nodes.get(key) if existing is not None: existing.value = value self._unlink(existing) self._push_front(existing) return # Case 2: New key when cache is full -> evict the least recently used node before `tail`. if len(self.nodes) == self.capacity: lru_node = self.tail.prev assert lru_node is not None and lru_node is not self.head self._unlink(lru_node) del self.nodes[lru_node.key] # Insert the new node into both the dict and the front of the recency list. new_node = CacheNode(key, value) self.nodes[key] = new_node self._push_front(new_node)Part 1 library comparisons: Java `LinkedList` vs `LinkedHashMap`
The prompt asks two classic engineering design questions about standard-library containers:
- Why Java's
java.util.LinkedListis NOT appropriate: Even thoughjava.util.LinkedListis a doubly linked list internally, its internalNode<E>class isprivateand never returned to callers. That means aHashMapcannot store a direct pointer to a key's list node! Moving a key to the front requireslist.remove(key), which walks the list from one end inO(n)time, breaking theO(1)requirement. (Storing aListIteratorfails too, because modifying the list invalidates every other iterator withConcurrentModificationException.) - Comparing custom map + list against
LinkedHashMap(and Python'sOrderedDict): Java'sLinkedHashMapis literally a hash table whose entries are threaded together by a doubly linked list. Constructingnew LinkedHashMap<>(capacity, 0.75f, true)setsaccessOrder = true(moving entries to the end on bothgetandput), and overridingremoveEldestEntryto returnsize() > capacityimplements a completeO(1)LRU cache in ~10 lines (Python'scollections.OrderedDictdoes the same viamove_to_endandpopitem(last=False)).- Trade-offs: In production code,
LinkedHashMap/OrderedDictis shorter, battle-tested, and has lower per-entry object overhead. Building from scratch gives full control (custom eviction callbacks, size-weighted eviction by bytes rather than entry count, or fine-grained locking) and demonstrates the exact pointer mechanics interviewers want to verify. Note that neither is thread-safe out of the box, and inaccessOrdermode evenget()structurally modifies the linked list, so iterating without locking throwsConcurrentModificationException.
- Trade-offs: In production code,
- Why Java's
Part 2 why naive search repeats work
Now consider
combination_sum(candidates, target). If we recursively try every candidate at every step while keeping the running sum at mosttarget: - Forcandidates = [3, 4, 6]andtarget = 12, the search builds[3, 3, 6],[3, 6, 3], and[6, 3, 3]separately — doing up tok!redundant work for a combination of lengthkand requiring a set of sorted tuples afterward to deduplicate. - Alternatively, trying every count tuple(c_1, c_2, ..., c_n)up totarget // candidatevisits the full Cartesian product of counts, testing many combinations whose sum overshootstargetimmediately.We want an algorithm that builds each unique multiset (a collection where elements may repeat, like
{3, 3, 6}, but order does not matter) at most once and stops exploring a branch the moment its sum exceedstarget.Part 2 key idea: sorted backtracking with non-decreasing choices
Every multiset has exactly one sorted (non-decreasing) arrangement:
{3, 3, 6}has only[3, 3, 6]. So if we forbid our search from ever picking a smaller number after a larger one, duplicates become impossible!We use backtracking (incrementally extending a single
current_pathlist, recursing, and popping the last choice on return) combined with three pruning rules (cutting off futile branches immediately):- Deduplicate and sort (
sorted_values = sorted(set(candidates))): Removing duplicate input numbers ensures[2, 2]incandidatescannot start two identical2branches, and sorting puts numbers in ascending order. - Enforce non-decreasing order with
start_index: A call atstart_indexonly loopsidxfromstart_indexupward. When we picksorted_values[idx], we recurse withstart_index = idx(notidx + 1!) so the same number can be reused again, while earlier smaller numbers are locked out forever. - Break early when
amount > remaining: Becausesorted_valuesis sorted ascending, the momentsorted_values[idx] > remaining, every candidate further right in the loop is even larger and guaranteed to overshoot too — so webreakout of theforloop immediately instead of merelycontinue-ing.
Why backtracking over Dynamic Programming (DP) here? A bottom-up DP builds and stores the full list of combinations for every intermediate sum
1, 2, ..., target. Many of those intermediate combinations can never reachtarget(for instance, odd sums or sums neartargetwith no matching gap), yet DP allocates memory for all of them. Backtracking keeps only onecurrent_pathlist of length at mosttarget / min_candidatein working memory alongside the output. (DP is superior when you only need the count of combinations or aTrue/Falsereachability check, which takesO(N * target)time andO(target)space.)- Deduplicate and sort (
Code `combination_sum`
Notice
combinations.append(list(current_path))at the base case:current_pathis mutated throughout the search via.append()and.pop(), so we must save a shallow copylist(current_path)rather than appending a reference tocurrent_pathitself.from typing import List def combination_sum(candidates: List[int], target: int) -> List[List[int]]: # Guard against 0 or negative amounts, which would allow infinite-length combinations. for amount in candidates: if amount <= 0: raise ValueError("all candidate amounts must be positive integers") if target < 0: return [] # Deduplicate so repeated inputs cannot build duplicate combinations, and sort ascending # so we can stop scanning a loop immediately once `amount > remaining`. sorted_values = sorted(set(candidates)) # combinations: completed valid combinations, e.g. [[3, 3, 4], [3, 7]]. combinations: List[List[int]] = [] # current_path: single active combination being explored along the current recursion branch. current_path: List[int] = [] def backtrack(start_index: int, remaining: int) -> None: # Base case: exact match found; append a snapshot copy because `current_path` mutates later. if remaining == 0: combinations.append(list(current_path)) return # Only consider indices >= start_index so combinations stay non-decreasing (no permutations). for idx in range(start_index, len(sorted_values)): amount = sorted_values[idx] if amount > remaining: # Pruning: `sorted_values` is ascending, so all later amounts are also > remaining. break current_path.append(amount) # Pass `idx` (not `idx + 1`) because the same candidate amount may be reused unlimited times. backtrack(idx, remaining - amount) current_path.pop() backtrack(0, target) return combinationsTrace Example 2 on the backtracking tree
Let's trace
candidates = [3, 4, 6]andtarget = 12(sorted_values = [3, 4, 6]). Each node shows(current_path, remaining, allowed values):([], rem=12, allow [3,4,6]) ├── pick 3 -> ([3], rem=9, allow [3,4,6]) │ ├── pick 3 -> ([3,3], rem=6, allow [3,4,6]) │ │ ├── pick 3 -> ([3,3,3], rem=3, allow [3,4,6]) │ │ │ ├── pick 3 -> ([3,3,3,3], rem=0) ==> RECORD [3, 3, 3, 3] │ │ │ └── try 4 > 3: BREAK (skips 4 and 6) │ │ ├── pick 4 -> ([3,3,4], rem=2, allow [4,6]) │ │ │ └── try 4 > 2: BREAK (skips 4 and 6) │ │ └── pick 6 -> ([3,3,6], rem=0) ==> RECORD [3, 3, 6] │ ├── pick 4 -> ([3,4], rem=5, allow [4,6]) │ │ ├── pick 4 -> ([3,4,4], rem=1, allow [4,6]) │ │ │ └── try 4 > 1: BREAK │ │ └── try 6 > 5: BREAK │ └── pick 6 -> ([3,6], rem=3, allow [6]) │ └── try 6 > 3: BREAK ├── pick 4 -> ([4], rem=8, allow [4,6]) <-- 3 is no longer allowed! │ ├── pick 4 -> ([4,4], rem=4, allow [4,6]) │ │ ├── pick 4 -> ([4,4,4], rem=0) ==> RECORD [4, 4, 4] │ │ └── try 6 > 4: BREAK │ └── pick 6 -> ([4,6], rem=2, allow [6]) │ └── try 6 > 2: BREAK └── pick 6 -> ([6], rem=6, allow [6]) └── pick 6 -> ([6,6], rem=0) ==> RECORD [6, 6]Because
3is disallowed once4or6is chosen,[6, 3, 3]is never even attempted, and the answers emerge naturally in sorted order:[[3, 3, 3, 3], [3, 3, 6], [4, 4, 4], [6, 6]].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # ---------- Part 1: O(1) Least Recently Used (LRU) Cache ---------- class CacheNode: """One node in the doubly linked recency list, storing both key and value.""" def __init__(self, key: int = 0, value: int = 0): # Storing `key` on the node lets us delete `nodes[oldest.key]` in O(1) on eviction. self.key = key self.value = value self.prev: Optional["CacheNode"] = None self.next: Optional["CacheNode"] = None class LRUCache: """In-memory LRU cache supporting O(1) average get(key) and put(key, value).""" def __init__(self, capacity: int): self.capacity = capacity # nodes: dict mapping key -> CacheNode for O(1) direct node lookup. self.nodes: Dict[int, CacheNode] = {} # Dummy sentinel nodes frame the list: # head <-> [most recently used] <-> ... <-> [least recently used] <-> tail # Sentinels guarantee every real node has non-None neighbors, eliminating edge-case branches. self.head = CacheNode() self.tail = CacheNode() self.head.next = self.tail self.tail.prev = self.head def _unlink(self, node: CacheNode) -> None: """Bridge `node`'s neighbors directly to each other in O(1).""" prev_node = node.prev next_node = node.next assert prev_node is not None and next_node is not None prev_node.next = next_node next_node.prev = prev_node def _push_front(self, node: CacheNode) -> None: """Insert `node` right after dummy `head` (marking it most recently used) in O(1).""" first_real = self.head.next assert first_real is not None node.prev = self.head node.next = first_real self.head.next = node first_real.prev = node def get(self, key: int) -> int: node = self.nodes.get(key) if node is None: return -1 # Reading a key counts as a use, so move its node to the front. self._unlink(node) self._push_front(node) return node.value def put(self, key: int, value: int) -> None: if self.capacity <= 0: return # Case 1: Key already exists -> update value in place and refresh recency (no eviction). existing = self.nodes.get(key) if existing is not None: existing.value = value self._unlink(existing) self._push_front(existing) return # Case 2: New key when cache is full -> evict the least recently used node before `tail`. if len(self.nodes) == self.capacity: lru_node = self.tail.prev assert lru_node is not None and lru_node is not self.head self._unlink(lru_node) del self.nodes[lru_node.key] # Insert the new node into both the dict and the front of the recency list. new_node = CacheNode(key, value) self.nodes[key] = new_node self._push_front(new_node) # ---------- Part 2: Unique Target-Sum Combinations ---------- def combination_sum(candidates: List[int], target: int) -> List[List[int]]: # Guard against 0 or negative amounts, which would allow infinite-length combinations. for amount in candidates: if amount <= 0: raise ValueError("all candidate amounts must be positive integers") if target < 0: return [] # Deduplicate so repeated inputs cannot build duplicate combinations, and sort ascending # so we can stop scanning a loop immediately once `amount > remaining`. sorted_values = sorted(set(candidates)) # combinations: completed valid combinations, e.g. [[3, 3, 4], [3, 7]]. combinations: List[List[int]] = [] # current_path: single active combination being explored along the current recursion branch. current_path: List[int] = [] def backtrack(start_index: int, remaining: int) -> None: # Base case: exact match found; append a snapshot copy because `current_path` mutates later. if remaining == 0: combinations.append(list(current_path)) return # Only consider indices >= start_index so combinations stay non-decreasing (no permutations). for idx in range(start_index, len(sorted_values)): amount = sorted_values[idx] if amount > remaining: # Pruning: `sorted_values` is ascending, so all later amounts are also > remaining. break current_path.append(amount) # Pass `idx` (not `idx + 1`) because the same candidate amount may be reused unlimited times. backtrack(idx, remaining - amount) current_path.pop() backtrack(0, target) return combinations✅ Submit now — all tests should pass.
Intuition & how it works
Each half of this problem rests on one clean mental model:
- Part 1 — Least Recently Used (LRU) cache (a fixed-size cache that discards whichever item has gone untouched for the longest time when full): imagine a stack of folders on your desk paired with an index-card box. Whenever you read or update a folder, the index card (dict) points straight to that folder inside the stack (doubly linked list, where each item links to both its neighbor above and its neighbor below) so you can pull it out and place it on top in one step. When the desk hits capacity, the folder sitting at the very bottom (tail.prev) is guaranteed to be the least recently used one, so you drop it immediately.
- Part 2 — Target-sum combinations: imagine making exact change for 10 euros using 3, 4, and 7-euro transfer amounts with backtracking (trying one amount at a time, moving forward, and undoing the last choice whenever we hit 10 or overshoot). To never generate rearranged duplicates like [3, 4, 3] and [4, 3, 3], enforce one rule: never pick a smaller amount after a larger one. Once you place 4, you may only place 4 or 7 from that point onward.
Why do naive approaches fail? In Part 1, a dictionary alone cannot find the oldest entry without scanning every key in O(capacity) time, while a plain list/array requires O(capacity) scanning or shifting to find and move a key (and Java's java.util.LinkedList hides its internal node objects, forcing O(n) linear search on remove(key)). In Part 2, branching on all candidates at every depth explores up to k! permutations of every length-k combination and keeps testing larger numbers even after a smaller number already exceeded the remaining target.
Let's walk through a tiny example of each:
- LRU (capacity = 2): put(1, 10) -> list [1]; put(2, 20) -> list [2, 1] (2 is newest, 1 is oldest); get(1) returns 10 and moves 1 to the front -> list [1, 2]; put(3, 30) sees capacity 2 is full, evicts 2 from the back (tail.prev), and inserts 3 at the front -> list [3, 1].
- Combinations (candidates = [3, 4, 7], target = 10): Starting at [] (remaining = 10), we try 3 -> [3, 3, 3] (remaining = 1, next 3 > 1 breaks), back up to [3, 3] (remaining = 4), try 4 -> [3, 3, 4] (remaining = 0, record [3, 3, 4]), and 7 > 4 breaks. Backing up to [3] (remaining = 7), [3, 4] (remaining = 3, 4 > 3 breaks), then [3, 7] (remaining = 0, record [3, 7]). Finally [4, 4] (remaining = 2, 4 > 2 breaks) and [7] (remaining = 3, 7 > 3 breaks), returning [[3, 3, 4], [3, 7]].
Complexity
Part 1 (LRUCache with capacity C):
- Time: O(1) average per get and put. Each call performs one hash-table lookup (plus at most one insertion and one deletion on eviction), which is O(1) on average, and rewires a constant number (4 to 6) of prev/next pointers in the doubly linked list.
- Space: O(C). The cache stores at most C CacheNode objects and C dictionary entries, plus two fixed dummy sentinel nodes (head and tail, placeholder nodes that hold no user data).
Part 2 (combination_sum with N distinct candidates, target T, and smallest candidate M):
- Time: O(N log N + K * (T / M)) output-sensitive, and O(N^(T / M)) loose worst-case upper bound (more tightly bounded by the number of non-decreasing multisets whose sum is <= T). Deduplicating and sorting takes O(N log N). In the search tree, every recursive call represents a distinct non-decreasing prefix with sum <= T of depth at most T / M, doing O(1) work per child branch plus at most one pruned break check, and copying each of the K valid combinations takes O(T / M) time. Because the number of valid combinations itself can grow exponentially (for 1..T, it equals the integer partitions of T), no algorithm that lists every combination can beat exponential worst-case time.
- Space: O(N + T / M) auxiliary working space (excluding the output list). sorted_values stores at most N distinct ints, while current_path and the recursion call stack hold at most T / M frames along the single active root-to-leaf branch.
Edge cases
- Empty
candidates([]) or unreachabletarget([4, 6]withtarget = 5): Loops zero times or prunes all branches and returns[]. - Duplicate values in
candidates([3, 4, 3, 4]withtarget = 10): Deduplicating withset(candidates)ensures[3, 3, 4]is emitted once instead of multiple times. - Unsorted
candidates([7, 4, 3]): Sorting upfront ensures earlybreakpruning is sound and combinations come out in ascending lexicographic order. - Candidate equal to
target([5]withtarget = 5): Produces[[5]]of length 1. target == 0vstarget < 0:target < 0returns[];target == 0hits the base case immediately and returns[[]](the single empty multiset summing to0— always clarify with the interviewer whethertarget == 0is possible and whether[]or[[]]is preferred). Non-positive candidates (<= 0) raiseValueErrorbecause0with unlimited reuse yields infinitely many combinations.- Deep recursion when
M = 1andTis large: Recursion depth reachesT / M; ifT > 1000with candidate1, an explicit stack avoids Python's ~1,000-frame recursion limit. - LRU edge cases (
capacity <= 0,capacity = 1, updating an existing key): Withcapacity <= 0,putis a safe no-op andgetreturns-1; withcapacity = 1, every new key evicts the sole entry; updating an existing key updates its value and moves it to the front without evicting anything.
Common mistakes
- Recursing with
idx + 1instead ofidxin Part 2: Passingidx + 1forbids reusing the same candidate, dropping[3, 3, 4]in Example 1. - Looping from
0instead ofstart_index: Generates every permutation ([3, 3, 6],[3, 6, 3],[6, 3, 3]), blowing up runtime by up tok!. - Using
breakwithout sortingcandidatesfirst: On unsorted[7, 3]withtarget = 6, seeing7 > 6and breaking skips3behind it and misses[3, 3]. - Appending
current_pathinstead oflist(current_path): Appends aliases to the same mutable list, which gets popped back to[]by the end of the search, leaving[ [], [] ]. - Forgetting
keyinsideCacheNode: When evictingself.tail.prev, you have the node object inO(1), but withoutlru_node.keyyou cannot delete its entry fromself.nodesinO(1). - Not moving nodes to the front on
get(key): A cache hit is a recent use; leaving the node in place turns LRU into FIFO (First-In, First-Out) eviction. - Evicting on
put(existing_key, new_value)whenlen(nodes) == capacity: Updating an existing key does not add a new key, so checking capacity before checkingkey in self.nodeswrongly deletes a valid entry.
Alternative approaches
- Library
OrderedDict/LinkedHashMapfor Part 1: Python'scollections.OrderedDictmaintains a doubly linked list internally (move_to_end(key)onget/putandpopitem(last=False)on overflow), matching Java'sLinkedHashMap(capacity, 0.75f, true)withremoveEldestEntry. Prefer this in production unless custom node behavior is required; writeCacheNode+ dummy sentinels in interviews when asked to implement from scratch. - Bottom-up Dynamic Programming (DP) for Part 2: Maintain
dp[s]= list of ascending combinations summing tosfor0 <= s <= target. Iteratefor amount in sorted_values:in the outer loop (preventing permutations!) andfor s in range(amount, target + 1):in the inner loop, appendingcombo + [amount]for eachcomboindp[s - amount]. While correct, DP materializes combination lists for every intermediate sum1 .. target - 1even when most cannot reachtarget, consuming far more memory than backtracking's singlecurrent_path.
Follow-up questions
- How would the combination search change if each input element could be used at most once and the input list contained duplicates? Sort
candidateswithout callingset()(so[1, 1, 6]keeps both1s), recurse withidx + 1instead ofidxso each list element is used at most once, and addif idx > start_index and candidates[idx] == candidates[idx - 1]: continueinside the loop. That one check allows two equal numbers at different depths in the same combination ([1, 1, 6]), while preventing the second1from starting an identical sibling subtree at the same depth. - If callers only needed the total number of distinct combinations rather than listing them all, how would you compute it faster? Switch from backtracking to 1D coin-change dynamic programming (solving larger targets from cached counts of smaller targets): initialize
ways = [1] + [0] * target, then runfor amount in sorted(set(candidates)):outside andfor s in range(amount, target + 1): ways[s] += ways[s - amount]inside. Putting candidates in the outer loop counts unordered combinations rather than ordered sequences, running inO(N * target)time andO(target)space with zero exponential blowup. - How would you adapt the LRU cache so many threads can read and write concurrently with low lock contention? Because even
get(key)mutatesprev/nextpointers in the doubly linked list, a read-write lock does not allow concurrent reads — the simplest correct fix wrapsgetandputin a single mutex (threading.Lock). To scale across many CPU cores without one global lock becoming a contention bottleneck, partition the key space intoSindependent shards (for exampleS = 64smallerLRUCache(capacity // S)instances chosen byhash(key) % S), each protected by its own lock, trading exact global LRU forS-way segmented LRU withStimes less lock contention.
Follow-up questions
- How would the combination search change if each input element could be used at most once and the input list contained duplicates?
- If callers only needed the total number of distinct combinations rather than listing them all, how would you compute it faster?
- How would you adapt the LRU cache so many threads can read and write concurrently with low lock contention?
Similar questions
- Real-Time Card Fraud Detection Pipeline
- Technical Architecture and Personal Ownership Deep Dive
- Distributed LRU Cache and Transfer-Matching API
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses