Coding and Data Structures Interview Questions
Short answers to 12 coding and data structures interview questions.
Questions and answers (12)
Answers are written in plain English and reviewed for technical accuracy. Each answer states the point first, then the reason.
1. Implement scaled dot-product attention with a causal mask, from scratch, in NumPy or PyTorch.
Scale QK^T by 1/sqrt(d), add a causal mask, then apply softmax and multiply by V. The mask sets future positions to -inf before the softmax. The scale keeps the logits small and stops softmax saturation. Cost grows with sequence length squared.
s = q @ k.T / d**0.5
s = s.masked_fill(causal_mask, float('-inf'))
p = torch.softmax(s, dim=-1)
out = p @ v
2. Implement multi-head attention, then convert it to grouped-query attention.
Split Q, K and V into heads, run attention per head, then concatenate and project. For grouped-query attention, use fewer K and V heads and repeat each one across a group of Q heads. This shrinks the KV cache and cuts memory traffic during decode.
q = q.view(B, T, H, D).transpose(1, 2)
k = k.view(B, T, G, D).transpose(1, 2)
k = k.repeat_interleave(H // G, dim=1)
out = attn(q, k, v).transpose(1, 2).reshape(B, T, H * D)
3. Implement a KV cache and single-step decode.
Store past K and V tensors per layer and append the new step each time. Decode then attends over the cache plus the new token only. This turns per-step cost from O(T) to O(1) attention work over stored keys. The cache grows with context length.
k = torch.cat([cache_k, k_new], dim=2)
v = torch.cat([cache_v, v_new], dim=2)
cache_k, cache_v = k, v
out = attn(q_new, k, v)
4. Implement BPE training and encoding from scratch.
Start with byte symbols, count adjacent pairs, and merge the most frequent pair into a new token. Repeat for a fixed number of merges to build the vocabulary. Encoding applies the learned merges in order. The tokenizer must apply merges in the same order as training.
for _ in range(num_merges):
pairs = count_pairs(ids)
best = max(pairs, key=pairs.get)
ids = merge(ids, best)
merges[best] = len(merges)
5. Implement top-k, top-p and temperature sampling over a logits vector.
Divide logits by temperature, then keep the top-k values or the smallest set whose probability mass reaches p. Renormalize and sample from the result. Temperature below 1 sharpens the distribution and above 1 flattens it. Top-p adapts the cutoff size to the distribution shape.
logits = logits / temperature
kth = torch.topk(logits, k).values[..., -1]
logits[logits < kth] = float('-inf')
probs = torch.softmax(logits, dim=-1)
idx = torch.multinomial(probs, 1)
6. Implement an LRU cache with O(1) get/put, then add TTL.
Combine a hash map with a doubly linked list so get and put run in O(1). Move a hit node to the front and evict the tail node on overflow. For TTL, store an expiry time per node and check it on get. A lazy check is simple but stale entries stay in memory until eviction.
def get(self, key):
node = self.map.get(key)
if node is None or node.exp < time.time():
return None
self._move_front(node)
return node.val
7. Implement a token-bucket rate limiter, then make it distributed.
Each key holds a bucket of tokens that refills at a fixed rate. A request takes tokens only when enough remain. For a distributed version, keep the bucket in Redis and run the check and update as one atomic Lua script. This keeps the limit correct across many servers.
local t = redis.call('TIME')
local now = t[1] + t[2] / 1e6
-- refill, then take tokens only if enough remain
return allowed
8. Write an async batch processor over an API with concurrency limits, retries with jitter and error isolation.
Use a semaphore to cap in-flight calls and a queue to feed workers. Wrap each call in a retry loop with exponential backoff plus random jitter. Catch errors per item so one failure does not stop the batch. Return results and errors as separate lists.
async with sem:
for attempt in range(retries):
try:
return await call(item)
except Exception:
await asyncio.sleep(base * 2**attempt + random.random())
9. Write a streaming SSE/JSON parser that handles arbitrary chunk boundaries.
Keep a buffer and parse only complete events. Split on the blank line that ends each SSE event. Keep the rest of the buffer for the next chunk. This handles any chunk boundary because you never parse a partial event.
buf = ""
for chunk in stream:
buf += chunk
while "\n\n" in buf:
raw, buf = buf.split("\n\n", 1)
data = [l[5:] for l in raw.split("\n") if l.startswith("data:")]
yield json.loads("".join(data))
10. Implement a text chunker with overlap that never splits a semantic unit.
Split text into sentences first, then pack whole sentences into chunks up to a size limit. Repeat the last N characters of the previous chunk as overlap. This never splits a sentence, but overlap can duplicate a full sentence at a boundary.
sents = split_sentences(text)
chunks, cur = [], ""
for s in sents:
if len(cur) + len(s) > size and cur:
chunks.append(cur)
cur = cur[-overlap:]
cur += s
chunks.append(cur)
11. Implement cosine similarity search over embeddings, then explain why you would not ship it.
Normalize each vector and take the dot product with the query vector. Sort the scores and return the top k. Do not ship this because it scans every vector on each query. At 10 million vectors this costs 10 million dot products per request.
import numpy as np
M = np.array(embeddings)
M = M / np.linalg.norm(M, axis=1, keepdims=True)
q = query / np.linalg.norm(query)
scores = M @ q
top = np.argsort(-scores)[:k]
12. Implement a minimal agent loop with tool dispatch, error handling and a step budget.
Loop until the model returns no tool call or the step budget runs out. Dispatch each tool call by name and catch errors as text. Return the error to the model so it can recover. A budget of 10 steps stops runaway loops.
for step in range(budget):
msg = llm(messages)
if not msg.tool_calls:
return msg.content
for call in msg.tool_calls:
try:
out = tools[call.name](**call.args)
except Exception as e:
out = f"error: {e}"
messages.append(tool_result(call.id, out))