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:

  1. Part 1 — Constant-Time LRU Cache (LRUCache): Design a fixed-capacity in-memory key-value store supporting get(key) and put(key, value) in O(1) average time. Whenever inserting a new key would exceed capacity, evict whichever stored key has gone unaccessed (by both get and put) 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 dummy head and tail sentinel 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 to O(n) updates, compare building from scratch against built-in access-ordered maps (LinkedHashMap in Java or OrderedDict in Python), and analyze time and space complexity.
  2. Part 2 — Unlimited-Reuse Target Sum (combination_sum): Given a list of positive integer amounts candidates and an integer target, implement combination_sum(candidates, target) to return all unique combinations of values chosen from candidates whose sum equals target.

    • 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 candidates must be a positive integer (amount >= 1; non-positive entries raise ValueError).
  • candidates is not guaranteed to be sorted and may contain repeated integers; repeated entries in candidates must not produce duplicate combinations in the output.
  • If target < 0 or no multiset sums to target, return [].

Step-by-step walkthrough

  1. Understand both parts of the interview prompt

    This question combines two classic building blocks often paired in technical screens:

    1. Part 1 — In-memory LRU cache: Design a fixed-capacity key-value cache supporting get(key) and put(key, value) in O(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 both get and put for the longest time.
    2. Part 2 — Target-sum combinations: Given positive transfer candidates and a target amount, return every unique combination of candidates summing to target, 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 both LRUCache and combination_sum in solution.py, along with the Java/library comparisons and Dynamic Programming trade-offs asked in the prompt.

  2. 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 in O(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 takes O(n) linear scanning.

    We get O(1) for everything by combining them: the dictionary maps key -> CacheNode, jumping straight to the node inside a doubly linked list (a chain where each node stores both prev and next pointers so it can unlink itself in O(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 (head and tail) 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 head and tail, so node.prev and node.next are never None. Unlinking any node or inserting right after head always updates the exact same four pointers. 2. Each CacheNode stores both key and value. When the cache is full, we find the oldest node at self.tail.prev in O(1), and reading lru_node.key tells us which entry to delete from self.nodes in O(1).

  3. 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)
    
  4. 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.LinkedList is NOT appropriate: Even though java.util.LinkedList is a doubly linked list internally, its internal Node<E> class is private and never returned to callers. That means a HashMap cannot store a direct pointer to a key's list node! Moving a key to the front requires list.remove(key), which walks the list from one end in O(n) time, breaking the O(1) requirement. (Storing a ListIterator fails too, because modifying the list invalidates every other iterator with ConcurrentModificationException.)
    • Comparing custom map + list against LinkedHashMap (and Python's OrderedDict): Java's LinkedHashMap is literally a hash table whose entries are threaded together by a doubly linked list. Constructing new LinkedHashMap<>(capacity, 0.75f, true) sets accessOrder = true (moving entries to the end on both get and put), and overriding removeEldestEntry to return size() > capacity implements a complete O(1) LRU cache in ~10 lines (Python's collections.OrderedDict does the same via move_to_end and popitem(last=False)).
      • Trade-offs: In production code, LinkedHashMap / OrderedDict is 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 in accessOrder mode even get() structurally modifies the linked list, so iterating without locking throws ConcurrentModificationException.
  5. 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 most target: - For candidates = [3, 4, 6] and target = 12, the search builds [3, 3, 6], [3, 6, 3], and [6, 3, 3] separately — doing up to k! redundant work for a combination of length k and requiring a set of sorted tuples afterward to deduplicate. - Alternatively, trying every count tuple (c_1, c_2, ..., c_n) up to target // candidate visits the full Cartesian product of counts, testing many combinations whose sum overshoots target immediately.

    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 exceeds target.

  6. 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_path list, recursing, and popping the last choice on return) combined with three pruning rules (cutting off futile branches immediately):

    1. Deduplicate and sort (sorted_values = sorted(set(candidates))): Removing duplicate input numbers ensures [2, 2] in candidates cannot start two identical 2 branches, and sorting puts numbers in ascending order.
    2. Enforce non-decreasing order with start_index: A call at start_index only loops idx from start_index upward. When we pick sorted_values[idx], we recurse with start_index = idx (not idx + 1!) so the same number can be reused again, while earlier smaller numbers are locked out forever.
    3. Break early when amount > remaining: Because sorted_values is sorted ascending, the moment sorted_values[idx] > remaining, every candidate further right in the loop is even larger and guaranteed to overshoot too — so we break out of the for loop immediately instead of merely continue-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 reach target (for instance, odd sums or sums near target with no matching gap), yet DP allocates memory for all of them. Backtracking keeps only one current_path list of length at most target / min_candidate in working memory alongside the output. (DP is superior when you only need the count of combinations or a True/False reachability check, which takes O(N * target) time and O(target) space.)

  7. Code `combination_sum`

    Notice combinations.append(list(current_path)) at the base case: current_path is mutated throughout the search via .append() and .pop(), so we must save a shallow copy list(current_path) rather than appending a reference to current_path itself.

    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 combinations
    
  8. Trace Example 2 on the backtracking tree

    Let's trace candidates = [3, 4, 6] and target = 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 3 is disallowed once 4 or 6 is 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]].

  9. 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 unreachable target ([4, 6] with target = 5): Loops zero times or prunes all branches and returns [].
  • Duplicate values in candidates ([3, 4, 3, 4] with target = 10): Deduplicating with set(candidates) ensures [3, 3, 4] is emitted once instead of multiple times.
  • Unsorted candidates ([7, 4, 3]): Sorting upfront ensures early break pruning is sound and combinations come out in ascending lexicographic order.
  • Candidate equal to target ([5] with target = 5): Produces [[5]] of length 1.
  • target == 0 vs target < 0: target < 0 returns []; target == 0 hits the base case immediately and returns [[]] (the single empty multiset summing to 0 — always clarify with the interviewer whether target == 0 is possible and whether [] or [[]] is preferred). Non-positive candidates (<= 0) raise ValueError because 0 with unlimited reuse yields infinitely many combinations.
  • Deep recursion when M = 1 and T is large: Recursion depth reaches T / M; if T > 1000 with candidate 1, an explicit stack avoids Python's ~1,000-frame recursion limit.
  • LRU edge cases (capacity <= 0, capacity = 1, updating an existing key): With capacity <= 0, put is a safe no-op and get returns -1; with capacity = 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 + 1 instead of idx in Part 2: Passing idx + 1 forbids reusing the same candidate, dropping [3, 3, 4] in Example 1.
  • Looping from 0 instead of start_index: Generates every permutation ([3, 3, 6], [3, 6, 3], [6, 3, 3]), blowing up runtime by up to k!.
  • Using break without sorting candidates first: On unsorted [7, 3] with target = 6, seeing 7 > 6 and breaking skips 3 behind it and misses [3, 3].
  • Appending current_path instead of list(current_path): Appends aliases to the same mutable list, which gets popped back to [] by the end of the search, leaving [ [], [] ].
  • Forgetting key inside CacheNode: When evicting self.tail.prev, you have the node object in O(1), but without lru_node.key you cannot delete its entry from self.nodes in O(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) when len(nodes) == capacity: Updating an existing key does not add a new key, so checking capacity before checking key in self.nodes wrongly deletes a valid entry.

Alternative approaches

  • Library OrderedDict / LinkedHashMap for Part 1: Python's collections.OrderedDict maintains a doubly linked list internally (move_to_end(key) on get/put and popitem(last=False) on overflow), matching Java's LinkedHashMap(capacity, 0.75f, true) with removeEldestEntry. Prefer this in production unless custom node behavior is required; write CacheNode + 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 to s for 0 <= s <= target. Iterate for amount in sorted_values: in the outer loop (preventing permutations!) and for s in range(amount, target + 1): in the inner loop, appending combo + [amount] for each combo in dp[s - amount]. While correct, DP materializes combination lists for every intermediate sum 1 .. target - 1 even when most cannot reach target, consuming far more memory than backtracking's single current_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 candidates without calling set() (so [1, 1, 6] keeps both 1s), recurse with idx + 1 instead of idx so each list element is used at most once, and add if idx > start_index and candidates[idx] == candidates[idx - 1]: continue inside the loop. That one check allows two equal numbers at different depths in the same combination ([1, 1, 6]), while preventing the second 1 from 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 run for amount in sorted(set(candidates)): outside and for 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 in O(N * target) time and O(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) mutates prev/next pointers in the doubly linked list, a read-write lock does not allow concurrent reads — the simplest correct fix wraps get and put in a single mutex (threading.Lock). To scale across many CPU cores without one global lock becoming a contention bottleneck, partition the key space into S independent shards (for example S = 64 smaller LRUCache(capacity // S) instances chosen by hash(key) % S), each protected by its own lock, trading exact global LRU for S-way segmented LRU with S times less lock contention.

Follow-up questions

Similar questions

More Adyen interview questions

All 4 Adyen questions →