AI Interviews · Question

AI-assisted coding round: implement an LRU cache, then add per-entry TTL expiry, then make it thread-safe. One candidate recalls four staged parts. The CoderPad assistant answers in chat but cannot edit your code.

AI-assisted coding question reported at LinkedIn (Aug 2026). Sources, confidence and an answer card.

Researched · updated

r2b-001 AI Engineer AI-assisted coding rounds AI-assisted coding Medium confidence
On this page

What they’re really asking

If you only remember one thing, say this in the first minute: “I’ll type the basic LRU myself, a hash map plus a doubly linked list, because it’s short and the assistant’s classic bug is forgetting to delete the evicted key from the map. For expiry I pass the cache a clock, check it on get, and treat an entry as dead at exactly its expiry time. For threads I use one lock around get and put, because a read moves the entry in the list, so it’s a write. I’ll give the assistant small jobs with an easy check, like a fake clock or a stress test, not the cache itself.”

The rest of this page explains each part of that answer.

The interviewer wants three classic stages done under a clock, with an assistant you have to supervise.

A normal least-recently-used (LRU) cache question is one problem. This round is a staircase: plain LRU, then LRU with expiry, then something else, then thread safety. Each stage builds on the last, and you are scored partly on how far you climb. On top of that you may use an AI assistant, a chat tool built on a large language model (LLM) that can write code for you. That sounds like a speed-up. The reported experience is that it can be a slow-down, because every line it writes is a line you must check. Speed through stages 1 and 2 decides whether you ever reach the concurrency conversation.

The PracHub candidate (PracHub is a site where candidates share interview reports) lists LinkedIn’s tasks as standard LRU, LRU plus TTL, a third part they don’t remember, and thread safety. They chose Claude Opus 5 from CoderPad’s model list, finished two tasks and were rejected (PracHubfirst-hand · Aug 2026). Hello Interview’s summary of what LinkedIn looks for: “you’re not blindly accepting AI output” and “Can you reason about concurrency?” (Hello Interviewsecondary · 2026).

Words you need first

  • LRU (least recently used): when full, evict the entry unused for longest.
  • TTL (time to live): how long an entry stays valid after it is written. After that it is expired.
  • Lazy expiry: don’t hunt for expired entries; check the time when someone reads an entry, and delete it then if it’s dead.
  • An injected clock is a clock function passed into the cache, so tests can pass a fake one and move time without sleeping.

Clarify first

Spend one minute on the setup. Say your assumptions out loud:

  • TTL per entry or one for the whole cache? “I’ll assume per entry, set on put, and that reading an entry doesn’t extend its life.”
  • Is an entry alive at exactly its expiry time? “I’ll treat it as dead when now >= expires_at.”
  • Must expired entries be reclaimed eagerly? “I’ll start with lazy expiry, and prefer expired entries as victims when the cache is full.”
  • What concurrency? “I’ll assume threads in one process.”
  • What may the assistant do? Per Hello Interview it can’t edit your code (Hello Interviewsecondary · 2026). “Can it edit my file, or only chat?”

Answer

Follow one key through the three stages

A cache of capacity 2, with a fake clock that starts at 0.

StageWhat happensWhat to say in the interview
1put a, put b, get a, put c. The cache evicts b and deletes "b" from the map.”The node stores its key, so eviction can clean the map too.”
2At time 0, put d with a TTL of 5. The fake clock moves to 4.999: get d is a hit. It moves to 5.0: get d is a miss, and d is deleted.”Dead at exactly 5. My test sets the clock; it never sleeps.”
3Two threads call get a and put e at once. Both would rewire the same list.”One lock around both. A read moves the node, so a read-write lock won’t help.”

Stage 1: type it yourself (about 12 minutes)

A map plus a doubly linked list with sentinels: two dummy nodes at the ends that never hold data, so no code needs an “empty list” special case. The node keeps its key, so eviction deletes it from the map. This is the bug the candidate reports the assistant writing. Say: “I’ll type this part. It’s short, and I know where the bug lives.”

Stage 2: TTL with an injected clock

class TTLCache(LRUCache):
    def __init__(self, capacity, clock=time.monotonic):
        super().__init__(capacity)
        self.clock = clock                 # tests pass a fake; production uses monotonic time

    def get(self, key, default=None):
        n = self.map.get(key)
        if n is None:
            return default
        if n.expires_at is not None and self.clock() >= n.expires_at:
            self._unlink(n)
            del self.map[n.key]            # lazy expiry on read
            return default
        self._unlink(n)
        self._push_front(n)
        return n.val

    def put(self, key, val, ttl=None):
        exp = None if ttl is None else self.clock() + ttl
        ...                                # stage 1 put, storing exp on the node

Test the boundary exactly: alive at ttl − 0.001, gone at ttl, with a fake clock and no sleep. In production the clock is time.monotonic, a clock that only moves forward and ignores changes to the system time.

If time allows, add a min-heap of expiry times (a priority queue that always gives you the smallest item first). Then a full cache can drop dead entries before it evicts a live one. Without it, an expired entry nobody reads still takes a slot. When a key is overwritten, its old heap row stays behind; skip any row whose expiry no longer matches the node. Say: “Lazy expiry is correct. The heap is only so dead entries don’t push out live ones.”

Stage 3: thread safety

Put one lock around get and put, because get reorders the list. Then name the next steps. If one lock is contended, stripe by key hash: split the cache into shards, each with its own lock, and accept LRU per shard instead of across the whole cache.

Prove it with a stress test that checks the invariants (facts that must always hold: no duplicate keys, the map and list the same size, never above capacity) after 8 threads hammer the cache. In the family’s scratch run on 2026-10-12, an unlocked Python version broke its invariants in 6–9 of 20 runs even with the GIL enabled. The GIL (Python’s global interpreter lock, which lets one thread run bytecode at a time) doesn’t make a multi-step pointer update atomic. Say: “The GIL protects single steps, not a four-pointer splice.”

Using the assistant well here

Give it bounded jobs with an easy check:

  • “Write a fake clock class with a now I can set.”
  • “Write a test where 8 threads hammer this cache and then call check_invariants.”

Don’t ask it for the cache. Reviewing a generated cache costs more time than typing one, and the time you lose in stage 1 is the time you needed for stage 3.

Senior vs Staff

LRU, TTL, threads

Senior

  • Reaches stage 3 with tests, an injected clock and a correct lock, and catches the assistant's map-delete bug.

Staff

  • Also explains the expired-entries-occupy-capacity problem, why a read-write lock fails here, what striping trades, and how they'd verify it under load.

In plain terms: a Senior candidate finishes all three stages correctly. A Staff candidate also explains the less obvious problems (dead entries taking slots, why reads need an exclusive lock) and how they’d prove the cache works under load.

Small-team version

In production you’d use cachetools.TTLCache or a managed Redis with EX. The parts you own are the TTL value and the key.

  • Tie the TTL to how fast the source data changes. A cached answer about today’s prices needs a shorter life than one about a fixed document.
  • Put the prompt and model version in the key. A prompt change then can’t serve old answers.
  • Start short. Each hit saves one model call, about 1 cent at the walkthrough’s assumed request size. A shorter TTL costs you only the extra misses, so start short and lengthen it once you have a hit-rate number.
The arithmetic behind the numbers (for a Staff-level follow-up)
  • One model call: an assumed 3,000 input and 400 output tokens (a token is roughly ¾ of a word) at Claude Sonnet 5’s $2 / $10 per million list price (fetched 2026-10-11): (3,000 × $2 + 400 × $10) ÷ 1,000,000 = $0.010.

Pitfalls

  • time.time() inside the cache. Tests then need sleep and become slow and flaky.
  • An off-by-one at the expiry instant. Decide >= or > once, and test both sides of it.
  • A read lock around get. Two readers then rewire the list at the same time.
  • Letting the assistant generate stage 1. You then spend stage 2’s time debugging its eviction code.

Go deeper

Family

Caches in coding rounds: LRU and LFU, TTL, threads, snapshots and coalesced chunk fetches

Build an LRU cache, then add expiry, threads, save and restore, LFU, and a cache of 200 MB remote chunks that many callers miss at once. Get the core right fast, then reason about time, locks and bytes.

Other questions in this family