🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Interview: LRU Cache, Shortener, Rate Limiter

Python InterviewđŸŸĸ Free Lesson

Python Interview: LRU Cache, Shortener, Rate Limiter

Advanced Python interviews rarely fail candidates on syntax. They fail them on unexamined assumptions: a cache with linear eviction, a shortener whose codes are guessable, a rate limiter that is not thread-safe. The three questions below are the ones most likely to appear in a systems round, each solved in full with the reasoning an interviewer is listening for — complexity, concurrency, storage, and the failure modes you would handle in production.

What You'll Learn

  • 1Implement an LRU cache with O(1) get and put and explain the choice of data structures
  • 2Design a base62 shortener and discuss collision handling and code guessability
  • 3Write a thread-safe token bucket and justify its refill arithmetic
  • 4Structure a spoken answer that surfaces trade-offs before writing code

The shape of a strong answer

Interviewers score the conversation, not just the final function. A reliable structure takes ninety seconds of talking before any code: restate the problem and pin down the inputs, name the constraints out loud (expected scale, latency, consistency, concurrency), state the complexity you are aiming for, sketch the data structures, then write code and walk through one example by hand before optimising anything.

StageWhat you sayWhat it demonstrates
ClarifyScale, access pattern, concurrency, persistenceYou have built systems, not snippets
ApproachData structures and complexity targetYou can reason before typing
CodeSmall functions, clear namesYou write production-shaped code
VerifyOne example traced by hand, plus the edge caseYou do not trust yourself blindly
ImproveThe next bottleneck and its costYou know where you would stop

Question 1: an LRU cache with O(1) operations

The requirement is that get and put run in constant time, so a list scanned on every access is immediately wrong. The standard answer combines a hash map for lookup with a doubly linked list for recency order: the map finds the node in O(1), and unlinking plus re-inserting at the front is O(1) as well because the node already knows its neighbours.

python
class Node:
    __slots__ = ("key", "val", "prev", "next")

    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None


class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.map = {}
        self.head = Node()          # sentinel: head.next is the most recent
        self.tail = Node()          # sentinel: tail.prev is the victim
        self.head.next = self.tail
        self.tail.prev = self.head

    def _unlink(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def _push_front(self, node):
        node.next = self.head.next
        node.prev = self.head
        self.head.next.prev = node
        self.head.next = node

    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._unlink(node)
        self._push_front(node)
        return node.val

    def put(self, key, value):
        node = self.map.get(key)
        if node is not None:
            node.val = value
            self._unlink(node)
            self._push_front(node)
            return
        if len(self.map) >= self.capacity:
            victim = self.tail.prev
            self._unlink(victim)
            del self.map[victim.key]
        fresh = Node(key, value)
        self.map[key] = fresh
        self._push_front(fresh)


cache = LRUCache(2)
cache.put(1, "a")
cache.put(2, "b")
print(cache.get(1))      # a — 1 is now most recent
cache.put(3, "c")        # evicts key 2
print(cache.get(2))      # -1
print(cache.get(3))      # c

The sentinels are the trick that keeps the code branch-free: with dummy head and tail nodes there is no "is the list empty" case in unlink or insert. Expect the follow-up "what if two threads call put at once?" — the honest answer is a lock around both methods, or an OrderedDict with move_to_end plus popitem(last=False) if you may trade a little speed for far less code.

Question 2: a URL shortener with base62

The core is an encoding: turn an incrementing counter into a short alphabetic code, or hash the long URL and resolve collisions. Base62 over digits, lowercase, and uppercase gives roughly 3.5 trillion distinct codes in seven characters.

python
import string

ALPHABET = string.ascii_letters + string.digits


def base62(number: int) -> str:
    if number == 0:
        return ALPHABET[0]
    out = []
    while number:
        number, rem = divmod(number, 62)
        out.append(ALPHABET[rem])
    return "".join(reversed(out))


class Shortener:
    def __init__(self):
        self.counter = 0
        self.forward = {}
        self.reverse = {}

    def shorten(self, url: str) -> str:
        if url in self.reverse:
            return self.reverse[url]      # idempotent: one URL, one code
        self.counter += 1
        code = base62(self.counter)
        self.forward[code] = url
        self.reverse[url] = code
        return code

    def expand(self, code: str):
        return self.forward.get(code)


s = Shortener()
code = s.shorten("https://example.com/a/very/long/path?campaign=spring")
print(code, s.expand(code))
print(len(base62(10**12)))                # 7

Say the trade-offs without being asked. Sequential codes let anyone enumerate your links, so production systems either randomise the code or derive it from an keyed hash of the URL. Storing both directions needs a key-value store with a uniqueness constraint on the code, and the counter must be allocated atomically — a race produces two links with the same code, which is a correctness bug, not a cosmetic one. Finally, decide whether shortening is idempotent (cache the mapping) or always fresh (never reuse a code after deletion).

Question 3: a thread-safe token bucket

Rate limiting looks easy until the refill arithmetic is written without a lock or without accounting for elapsed time. A token bucket refills continuously at a fixed rate up to a capacity, and a request is allowed only when a token can be taken.

python
import threading
import time


class TokenBucket:
    def __init__(self, rate: float, capacity: int):
        self.rate = rate              # tokens added per second
        self.capacity = capacity
        self.tokens = float(capacity)
        self.updated = time.monotonic()
        self.lock = threading.Lock()

    def allow(self, cost: float = 1.0) -> bool:
        with self.lock:
            now = time.monotonic()
            elapsed = now - self.updated
            self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
            self.updated = now
            if self.tokens >= cost:
                self.tokens -= cost
                return True
            return False


bucket = TokenBucket(rate=2.0, capacity=3)
print([bucket.allow() for _ in range(5)])   # burst, then denial
time.sleep(0.6)
print(bucket.allow())                       # refilled by roughly one token

Three points separate a good answer here. Refilling must be lazy and derived from elapsed time rather than a background thread, time.monotonic() is required because wall-clock jumps would grant or deny tokens arbitrarily, and the lock covers read-modify-write of both tokens and updated. For a distributed system the same design moves to Redis with a single atomic script, because a lock in each process still permits one burst per process.

The edge cases that separate prepared candidates

Every one of these three problems has a small set of inputs that break a naive implementation, and raising them yourself scores more than getting the happy path right. For the cache, ask what happens at capacity zero — every insert would immediately evict, so either reject the capacity or allow exactly one entry — and whether get on a missing key should return a sentinel or raise, since that choice propagates into every caller. For the shortener, consider the empty or malformed URL, expanding a code that does not exist, and what shortening the same URL twice must return if links are shared. For the bucket, a cost larger than the capacity can never succeed and should be rejected at construction rather than silently denying forever.

Write the tests you would ship: a table-driven eviction sequence for the cache, an idempotency case and an unknown-code case for the shortener, and a refill test driven by a fake clock rather than by sleeping. Being able to list those tests before writing the code signals that you have debugged these systems in production rather than only in an interview.

Follow-ups interviewers actually ask

QuestionThe answer they want to hear
What is the space complexity?O(capacity) for the cache, O(n) for the shortener store
What if capacity is unbounded?Bounded by construction; unbounded caches are memory leaks
How do you make it persistent?A key-value store, with the counter allocated atomically
What breaks under concurrency?Name the shared fields and the lock or atomic operation that guards them
How would you test it?Table-driven cases for eviction, a fake clock for refill, a thread hammer for races
When would you not build this?When a managed service or library already meets the requirement

Behaviours that decide the offer

Talk through the trade-off before committing to an implementation; interviewers are listening for judgement, not recall. Name the complexity you are targeting and say it out loud when you achieve it. Handle the edge cases explicitly — capacity zero, repeated keys, a clock that moves backwards — because they are where production bugs live. Test with one example you trace by hand rather than asserting that it "should work". And when you get stuck, narrow the problem: replacing a linked list with an array of indices, or dropping thread-safety for the first draft, keeps the conversation moving instead of stalling on one detail.

Common Mistakes

Reaching for an OrderedDict without explaining why it is O(1)

Fix: State that move_to_end and popitem are constant time, and that the hash map still handles lookup

Writing a rate limiter that refills from a background thread

Fix: Refill lazily from elapsed time inside the lock; a timer thread adds scheduling jitter and another failure mode

Using time.time for token refill

Fix: Use time.monotonic so a system clock adjustment cannot grant or deny tokens unexpectedly

Producing sequential short codes with no discussion of enumeration

Fix: Mention randomised or keyed codes, idempotent shortening, and atomic counter allocation unprompted

Best Practices

  • Spend the first ninety seconds clarifying scale, concurrency, and persistence before writing code
  • Choose data structures by the operation you need — map for lookup, list for order — and say the complexity
  • Trace one example by hand through your code, then attack it with the nastiest edge case you can name
  • State what you would change in production: locks, storage, atomic counters, distributed coordination
  • End by naming the trade-off you deliberately accepted; it shows you know where the design stops being free

Interview Questions

Q1: Why a doubly linked list rather than a plain list for LRU order?

Because a plain list needs O(n) removal of an arbitrary element, while a doubly linked list with node pointers removes in O(1). The hash map stores the nodes, so lookup and unlink are both constant time.

Q2: How many unique short codes can seven base62 characters hold?

62 to the power of 7, about 3.5 trillion. Base62 avoids case-sensitivity problems in URLs while packing far more entropy than base62 alternatives such as hex.

Q3: Token bucket or fixed window for API limiting?

A token bucket allows controlled bursts at a smooth long-run rate, which suits APIs. Fixed windows are simpler but let a client send twice the limit across a window boundary; a sliding window fixes that at the cost of more state.

Q4: What changes when the rate limiter must work across several servers?

Per-process locks no longer give a global limit, so the check moves to a shared store — typically a Redis script that refills and decrements atomically — or to a centralised gateway.

Key Takeaways

  • O(1) LRU needs a hash map plus a doubly linked list, with sentinels to avoid empty-list branches
  • Base62 encoding gives short, case-safe codes; the real design work is collisions, persistence, and enumeration
  • A token bucket refills lazily from a monotonic clock and must guard its read-modify-write under a lock
  • Interviewers score clarity of trade-offs: complexity, concurrency, storage, and failure handling
  • Verify by tracing an example and then attacking the edge cases; untested confidence reads as inexperience
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement