Recency-Evicting Store and Random Gift-Swap Pairing
Data Structure DesignModel answerLast updated
Two short coding tasks: build a fixed-size store that drops the least recently touched key in constant time, and pair up participants from a CSV so nobody draws themselves.
This exercise has two independent parts. Use any language you like, and explain your design as well as writing the code.
Part 1: Fixed-size store with recency-based eviction
Build a class that holds integer key/value pairs up to a fixed size.
- The constructor takes a positive integer
capacity. get(key)returns the stored value, or-1if the key is absent.put(key, value)inserts a new pair or overwrites the value of an existing key.- If a new key is inserted while the store already holds
capacityentries, exactly one entry must be removed first: the one whose last use is the oldest. - A key counts as "used" whenever a
getfinds it or aputwrites it. After such an operation, that key is the freshest one. - Both
getandputmust run in amortized O(1) time. - Keys and values are integers, and there can be up to
10^5operations.
Skeleton:
class Cache:
def __init__(self, capacity: int):
...
def get(self, key: int) -> int:
...
def put(self, key: int, value: int) -> None:
...
Describe the data structures you chose and why they give constant-time behavior.
Part 2: Secret gift pairing from a CSV
The input is a CSV file with a header row name,email followed by one row per participant:
name,email
Alice,[email protected]
Bob,[email protected]
Charlie,[email protected]
Write a program that decides, for every participant, who they will buy a gift for. The rules are:
- Nobody may be assigned to themselves.
- Everyone gives to exactly one person.
- Everyone receives from exactly one person.
Write the result to a CSV, for example:
giver_name,giver_email,receiver_name,receiver_email
Alice,[email protected],Bob,[email protected]
Bob,[email protected],Charlie,[email protected]
Charlie,[email protected],Alice,[email protected]
Requirements:
- The file fits in memory. If it contains fewer than 2 participants, report an error.
- Names and emails are non-empty, and emails are unique.
- The solution should be fast for up to
10^4participants. - The pairing must be random. A fixed rotation of the input order is not acceptable unless you can justify that it is both random enough and free of self-assignments.
- A suggested signature:
def assign_gifts(input_csv_path: str, output_csv_path: str) -> None:
"""Read participants from input_csv_path and write assignments to output_csv_path."""
Explain why your method guarantees rules 1 to 3.
Hints
Hint 1
For Part 1, a dictionary alone gives O(1) lookup but no cheap way to know which key is oldest. Think about what second structure supports O(1) removal from the middle and O(1) insertion at one end, and what the dictionary should store so it can reach that structure directly.
Hint 2
Dummy head and tail nodes in the linked list remove the special cases for an empty list or for touching the first and last elements. Remember that a `put` on an existing key must refresh it and must never evict anything.
Hint 3
For Part 2, rules 2 and 3 say the assignment is a permutation, and rule 1 says it has no fixed points. Consider shuffling and rejecting bad results, and estimate how often that succeeds. Alternatively, think about a construction that forms one big cycle, which cannot contain a fixed point.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Recency-evicting store (LRU cache)
Approach
Two structures cooperate:
- A hash map from key to a list node gives O(1) lookup.
- A doubly linked list ordered by recency gives O(1) "move to freshest" and O(1) "remove oldest". The freshest node sits right after a dummy head, and the oldest sits right before a dummy tail.
Because the map holds node references, once we find a key we can unlink its node without scanning.
- get(key): if the key is missing, return
-1and change nothing. Otherwise unlink the node, reinsert it at the front, and return its value. - put(key, value): if the key exists, update the value and move the node to the front. Otherwise, if the size equals
capacity, unlink the node before the dummy tail and delete its key from the map. Then create the new node, add it to the map and put it at the front.
Why it is correct
The list order always reflects last use, since only successful get and put calls reorder it and each one moves the touched node to the front. So the node next to the tail is always the least recently used. Eviction occurs only for a new key in a full store, so the size never exceeds capacity, and overwriting never evicts.
Complexity
Time is O(1) per operation (constant pointer updates plus hash operations). Space is O(capacity).
Edge cases
capacity == 1: each new key replaces the previous one.- A missed
getmust not alter ordering. - Overwriting an existing key refreshes it without eviction.
-1is ambiguous only if callers store-1; the stated contract accepts this.
class _Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key=0, val=0):
self.key, self.val = key, val
self.prev = self.next = None
class Cache:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.cap = capacity
self.map = {}
self.head, self.tail = _Node(), _Node()
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, n):
n.prev.next, n.next.prev = n.next, n.prev
def _push_front(self, n):
n.prev, n.next = self.head, self.head.next
self.head.next.prev = n
self.head.next = n
def get(self, key):
n = self.map.get(key)
if n is None:
return -1
self._unlink(n)
self._push_front(n)
return n.val
def put(self, key, value):
n = self.map.get(key)
if n:
n.val = value
self._unlink(n)
self._push_front(n)
return
if len(self.map) == self.cap:
old = self.tail.prev
self._unlink(old)
del self.map[old.key]
n = _Node(key, value)
self.map[key] = n
self._push_front(n)
In Python, collections.OrderedDict (move_to_end, popitem(last=False)) is a valid shortcut, but you should be able to build the manual version.
Part 2: Gift pairing without self-assignment
Modeling
Giver-to-receiver is a function. Rules 2 and 3 make it a bijection, so it is a permutation of the participant indices. Rule 1 forbids fixed points, so it is a derangement. For n = 1 none exists, hence the error for fewer than 2 people.
Two standard methods
Rejection sampling. Shuffle the indices with Fisher-Yates and accept if perm[i] != i for every i; otherwise reshuffle. Conditioning a uniform permutation on being a derangement gives a uniform derangement. The acceptance probability is D_n / n!, which tends to 1/e (about 0.37), so about 2.7 shuffles are expected, and more than 20 attempts is very unlikely (below 0.01%). Expected time is O(n).
Single-cycle construction. Shuffle the participants into a random order, then let each give to the next one, with the last giving to the first. This is one cycle of length n >= 2, so no fixed point is possible. It takes deterministic O(n) time. The trade-off is that it only produces single-cycle derangements, not all of them, though many organizers like that because it avoids small loops such as A and B swapping. Note this is shifting a shuffled order, not the original input order, so it is not the predictable pattern the prompt forbids.
Correctness
permis a permutation, so each index appears once as giver and once as receiver (rules 2 and 3).- Only fixed-point-free permutations are accepted or constructed (rule 1).
- Identity is the row index, so duplicate names cannot break anything.
Implementation
import csv
import random
def random_derangement(n, rng):
if n < 2:
raise ValueError("need at least 2 participants")
perm = list(range(n))
while True:
rng.shuffle(perm)
if all(perm[i] != i for i in range(n)):
return perm
def assign_gifts(input_csv_path, output_csv_path, rng=None):
rng = rng or random.SystemRandom()
with open(input_csv_path, newline="", encoding="utf-8") as f:
rows = [(r["name"].strip(), r["email"].strip())
for r in csv.DictReader(f)]
if len(rows) < 2:
raise ValueError("need at least 2 participants")
if any(not n or not e for n, e in rows):
raise ValueError("blank name or email")
if len({e for _, e in rows}) != len(rows):
raise ValueError("duplicate email")
perm = random_derangement(len(rows), rng)
with open(output_csv_path, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["giver_name", "giver_email",
"receiver_name", "receiver_email"])
for i, j in enumerate(perm):
w.writerow([*rows[i], *rows[j]])
Complexity and practical notes
- Expected O(n) time and O(n) space, which is trivial at
10^4participants. - Accepting an injectable
rngmakes tests reproducible, whileSystemRandommakes real draws unpredictable. - Validate the header, blank fields and duplicates, and fail loudly: a silently wrong draw is worse than a crash.
- Common mistakes: rotating the unshuffled input by one, swapping elements only when they collide (which can bias the result or leave a fixed point at the end), and looping forever when
n == 1.