Category J · 29 Problems · Real Interview Questions
Live Company Questions
Real coding problems from actual interviews at Stripe, Anthropic, Datadog, Notion, Coinbase, Robinhood, DoorDash, Google, Samsara, and more. Each question is confirmed or closely extrapolated from reported live screens.
Problems: 29
Difficulty: Medium – Hard
Key patterns: text processing · log parsing · stream aggregation · data structure design
What this category is: These are company-flavored coding prompts — the same shapes you see on live screens: parse CSV and logs, simulate stacks and heaps, implement small services (rate limits, buffers, ledgers), and stitch streams. Use them to practice clean Python, edge cases, and clear reasoning under time pressure.
Parsing, CSV & markdown
P 56StripeCoding ProblemMedium
CSV Parsing and Processing
Given a CSV string with headers, implement process_csv(csv_string, operation, field). Operations: "sort" → sort rows by field descending, return sorted CSV string. "max" → return max value of numeric field. "min" → return min. "avg" → return average. Handle extra spaces and empty values. Don't use pandas.
csv.DictReaderio.StringIOsorted + lambdasum/len for avgstr.strip
Solution
import csv
from io importStringIOfrom typing importUniondefprocess_csv(csv_string: str, operation: str, field: str) -> Union[str, float, int]:
reader = csv.DictReader(StringIO(csv_string), skipinitialspace=True)
rows = [row for row in reader]
# Strip whitespace from all keys and values
rows = [{k.strip(): v.strip() for k, v in row.items()} for row in rows]
values = []
for row in rows:
val = row.get(field, "")
if val:
values.append(float(val))
if operation == "max":
returnint(max(values)) if values else0elif operation == "min":
returnint(min(values)) if values else0elif operation == "avg":
returnround(sum(values) / len(values), 1) if values else0.0elif operation == "sort":
sorted_rows = sorted(rows, key=lambda r: float(r.get(field, 0)), reverse=True)
header = ", ".join(sorted_rows[0].keys())
lines = [header]
for row in sorted_rows:
lines.append(", ".join(row.values()))
return"\n".join(lines)
csv.DictReader(StringIO(text), skipinitialspace=True) parses CSV from a string, handling spaces after commas. Strip all keys/values for safety. Extract numeric values with float(). For sort, rebuild the CSV string manually. This tests CSV parsing, type conversion, and string reconstruction — exactly the Stripe live coding pattern.
P 57SamsaraCoding ProblemMedium
Parse Markdown Links Without Regex
Convert simplified link syntax [text]("url") into HTML <a href="url">text</a> without using regex. Support multiple links per line, preserve non-link text, leave malformed patterns unchanged.
Example
parse_links('Click [Go]("example.com") and [Here]("other.com") now.')
→ 'Click <a href="example.com">Go</a> and <a href="other.com">Here</a> now.'
defparse_links(text):
result = []
i = 0while i < len(text):
if text[i] == '[':
# Try to match [text]("url")
close_bracket = text.find(']', i + 1)
if close_bracket == -1:
result.append(text[i])
i += 1continue# Check for ("...") immediately after ]if (close_bracket + 1 < len(text)
and text[close_bracket + 1:close_bracket + 3] == '("'):
close_paren = text.find('")', close_bracket + 3)
if close_paren != -1:
link_text = text[i + 1:close_bracket]
url = text[close_bracket + 3:close_paren]
result.append(f'<a href="{url}">{link_text}</a>')
i = close_paren + 2continue
result.append(text[i])
i += 1else:
result.append(text[i])
i += 1return''.join(result)
Scan character by character. When [ is found, look ahead for ] then ("..."). If the full pattern matches, emit an anchor tag. Otherwise, emit the character as-is. Using str.find() is cleaner than manual index tracking. The no-regex constraint forces explicit state transitions.
P 58AirbnbCoding ProblemMedium
CSV Slicer
Given a CSV string, extract specified rows and columns. Handle out-of-bounds gracefully (skip them). Return list of dicts.
csv.DictReaderio.StringIOindex bounds checkingselective field extraction
Solution
import csv
from io importStringIOdefcsv_slicer(csv_text, rows, columns):
reader = csv.DictReader(StringIO(csv_text))
all_rows = list(reader)
result = []
for row_idx in rows:
if row_idx < 0or row_idx >= len(all_rows):
continue
row = all_rows[row_idx]
sliced = {}
for col in columns:
if col in row:
sliced[col] = row[col]
if sliced:
result.append(sliced)
return result
Parse CSV into a list of dicts, then select rows by index and columns by name. Skip invalid indices and missing columns silently.
P 59Notion-styleCoding ProblemMedium
Markdown Table Parser
Parse a Markdown table string into a list of dicts. Handle alignment rows (containing ---, :---:, etc.) by skipping them. Strip whitespace from cells.
defparse_md_table(md_text):
lines = [l.strip() for l in md_text.strip().splitlines() if l.strip()]
iflen(lines) < 2:
return []
defparse_row(line):
cells = [c.strip() for c in line.split('|')]
return [c for c in cells if c] # remove empty strings from leading/trailing |defis_separator(line):
cells = parse_row(line)
returnall(set(c) <= set('-: ') for c in cells)
headers = parse_row(lines[0])
result = []
for line in lines[1:]:
if is_separator(line):
continue
values = parse_row(line)
row = dict(zip(headers, values))
result.append(row)
return result
Split on pipes, strip cells, detect separator rows, zip headers with values.
P 60Perplexity-styleCoding ProblemMedium
Error Pattern Clustering
Given JSON-lines error logs, cluster similar messages by replacing variable parts (numbers, IPs, UUIDs) with *. Count frequency per pattern. Return top N.
Example
errors = [ '{"message":"Connection to 10.0.0.1:5432 failed"}', ... ]
cluster_errors(errors, top_n=2)
→ [("Connection to *:* failed", 3), ("Timeout after * on request *", 2)]
re.sub for normalizationjson.loadsCounter.most_commonregex patterns
Normalize in order: IPs, UUIDs, hex, then bare numbers. Counter.most_common(n) returns top patterns.
Logs, time windows & streams
P 61AnthropicCoding ProblemHard
Exclusive Function Execution Time
Given function call logs "<id> <event> <timestamp>" where event ∈ {START, END}, compute the exclusive execution time for each function ID. Calls may be nested. Logs are chronological. Return a dict {id: exclusive_time}.
Example
logs = ["0 START 0", "1 START 2", "1 END 5", "0 END 6"]
# Function 0: total [0,6]=6, minus nested [2,5]=3 → exclusive = 3
# Function 1: [2,5]=3 → exclusive = 3
→ {0: 3, 1: 3}
from collections importdefaultdictdefexclusive_time(logs):
stack = [] # stack of (func_id, start_time)
result = defaultdict(int)
for log in logs:
parts = log.split()
func_id = int(parts[0])
event = parts[1]
timestamp = int(parts[2])
if event == "START":
if stack:
# Pause the currently running function
top_id, top_start = stack[-1]
result[top_id] += timestamp - top_start
stack[-1] = (top_id, timestamp) # update its start to now
stack.append((func_id, timestamp))
else: # END
fid, start = stack.pop()
result[fid] += timestamp - start + 1if stack:
# Resume parent: set its start to after this function ended
top_id, _ = stack[-1]
stack[-1] = (top_id, timestamp + 1)
returndict(result)
Use a stack to track active function calls. When a new function starts, pause the current top-of-stack by crediting its elapsed time. When a function ends, credit its time and resume the parent. The +1 accounts for inclusive timestamps. This is LeetCode 636 — a confirmed Anthropic onsite question.
P 62DatadogCoding ProblemHard
Log Store with Time-Range Queries
Implement a LogStore class: ingest(log_id, iso_timestamp) stores a log entry. query(start, end, granularity) returns log IDs where timestamp is in [start, end], grouped by granularity (YEAR, MONTH, DAY, HOUR, MINUTE). Return a dict of {bucket: [log_ids]}.
bisect for range queriesISO timestamp truncationdefaultdict(list)string slicing
Solution
from collections importdefaultdictfrom bisect import insort, bisect_left, bisect_right
GRANULARITY_SLICES = {
"YEAR": 4, "MONTH": 7, "DAY": 10, "HOUR": 13, "MINUTE": 16, "SECOND": 19,
}
classLogStore:
def__init__(self):
self.logs = [] # sorted list of (timestamp, log_id)defingest(self, log_id, timestamp):
insort(self.logs, (timestamp, log_id))
defquery(self, start, end, granularity):
left = bisect_left(self.logs, (start,))
right = bisect_right(self.logs, (end + "~",)) # ~ is after Z in ASCII
slice_len = GRANULARITY_SLICES[granularity]
buckets = defaultdict(list)
for i inrange(left, right):
ts, log_id = self.logs[i]
bucket_key = ts[:slice_len]
buckets[bucket_key].append(log_id)
returndict(buckets)
Store logs in a sorted list using bisect.insort for O(log n) insertion. For queries, use bisect_left/right to find the range, then iterate matching entries. Granularity is implemented by truncating timestamps. The "~" trick makes end inclusive since ~ sorts after timestamp characters.
P 63GoogleCoding ProblemHard
Detect RPC Timeouts in Event Stream
Given RPC log entries (rpc_id, timestamp, event_type) where event_type is "Start" or "End", and a timeout threshold, detect which RPCs have timed out. Report each timeout at the earliest possible timestamp. Return [(rpc_id, timeout_timestamp)].
dict with insertion orderingsliding expiry checkO(n) solution
Solution
defdetect_timeouts(events, timeout):
active = {} # rpc_id → start_timestamp (insertion-ordered in Python 3.7+)
timed_out = []
for rpc_id, timestamp, event_type in events:
# Check for timeouts among active RPCs
expired = []
for rid, start_ts in active.items():
if timestamp - start_ts >= timeout:
timed_out.append((rid, start_ts + timeout))
expired.append(rid)
for rid in expired:
del active[rid]
if event_type == "Start":
active[rpc_id] = timestamp
elif event_type == "End":
active.pop(rpc_id, None)
# Any remaining active RPCs: report their timeout timefor rid, start_ts in active.items():
timed_out.append((rid, start_ts + timeout))
returnsorted(timed_out, key=lambda x: x[1])
Maintain a dict of active RPCs. On each event, scan active RPCs for those exceeding the threshold. At the end, report still-active RPCs. Sort results by timeout timestamp.
P 64CoinbaseCoding ProblemEasy
Log Keyword Extractor
Given multiline log text and a list of keywords, extract all lines containing ANY keyword (case-insensitive). Return {keyword: [matching_lines]}.
from collections importdefaultdictdefextract_keywords(log_text, keywords):
result = defaultdict(list)
for line in log_text.strip().splitlines():
line_lower = line.lower()
for kw in keywords:
if kw.lower() in line_lower:
result[kw].append(line)
returndict(result)
For each line, check each keyword with in on the lowercased line. A line can match multiple keywords.
P 65BloombergCoding ProblemHard
Document Enrichment with Timeout
Given a stream of enrichment events {"document_id", "enricher_id", "enrichment", "timestamp"} and a set of required enricher IDs, accumulate per document. Emit when ALL required enrichers report OR after timeout_seconds since first enrichment. Missing enrichments are null.
Example
required = {"sentiment", "entities", "topics"}
events = [...] # d2 completes all three; d1 may timeout with topics=null
defaultdict with lambdasetdefaulttimeout trackingstream processing
Solution
from collections importdefaultdictdefprocess_enrichments(events, required_enrichers, timeout_seconds):
documents = {} # doc_id → {"first_ts": int, "enrichments": {enricher: data}}
emitted = []
for event in events:
doc_id = event["document_id"]
enricher = event["enricher_id"]
enrichment = event["enrichment"]
ts = event["timestamp"]
if enricher notin required_enrichers:
continueif doc_id notin documents:
documents[doc_id] = {"first_ts": ts, "enrichments": {}}
documents[doc_id]["enrichments"][enricher] = enrichment
# Check if all enrichers are present → emit immediatelyifset(documents[doc_id]["enrichments"].keys()) == required_enrichers:
emitted.append({
"document_id": doc_id,
"enricher_ids": list(required_enrichers),
"enrichments": documents[doc_id]["enrichments"],
})
del documents[doc_id]
continue# Check timeouts for all pending documents
timed_out = []
for did, doc in documents.items():
if ts - doc["first_ts"] >= timeout_seconds:
enrichments = {e: doc["enrichments"].get(e) for e in required_enrichers}
emitted.append({
"document_id": did,
"enricher_ids": list(required_enrichers),
"enrichments": enrichments,
})
timed_out.append(did)
for did in timed_out:
del documents[did]
# Emit remaining documents as timed outfor did, doc in documents.items():
enrichments = {e: doc["enrichments"].get(e) for e in required_enrichers}
emitted.append({
"document_id": did,
"enricher_ids": list(required_enrichers),
"enrichments": enrichments,
})
return emitted
Track first-seen timestamp per document. On each event: accumulate, emit if complete, then check pending docs for timeout. Flush remaining at end. Missing fields use dict.get → None.
P 66Perplexity-styleCoding ProblemMedium
Session Reconstruction from Logs
Given log entries {"user_id", "action", "timestamp"} (timestamp is int), group into sessions. A session ends after 1800 seconds (30 min) of inactivity. Return {user_id: [sessions]} where each session has start, end, actions.
Example
Gap > 1800s starts a new session per user.
defaultdict(list)sorted by timestampgap detectionsession boundary
Solution
from collections importdefaultdict
SESSION_TIMEOUT = 1800defreconstruct_sessions(logs):
# Group logs by user
user_logs = defaultdict(list)
for log in logs:
user_logs[log["user_id"]].append(log)
result = {}
for user_id, entries in user_logs.items():
entries.sort(key=lambda e: e["timestamp"])
sessions = []
current = {"start": entries[0]["timestamp"],
"end": entries[0]["timestamp"],
"actions": [entries[0]["action"]]}
for entry in entries[1:]:
if entry["timestamp"] - current["end"] > SESSION_TIMEOUT:
sessions.append(current)
current = {"start": entry["timestamp"],
"end": entry["timestamp"],
"actions": [entry["action"]]}
else:
current["end"] = entry["timestamp"]
current["actions"].append(entry["action"])
sessions.append(current)
result[user_id] = sessions
return result
Group by user, sort by time, split on gaps larger than SESSION_TIMEOUT.
P 67DatadogCoding ProblemMedium
Buffered Writer with Chunking
Implement BufferedWriter(write_fn, buffer_size): write(data) buffers data, flushing when buffer reaches capacity. flush() writes current buffer. close() flushes remaining and prevents further writes.
Example
chunks = []
writer = BufferedWriter(lambda data: chunks.append(data), buffer_size=10)
# after writes + close → chunks like ["hello worl", "d!!"]
Sorted (timestamp, value) lists per metric; bisect for window slice; aggregate stats.
Ledgers, trading & payments
P 69CoinbaseCoding ProblemMedium
Detect Double Spending in Ledger
Given a list of transactions {"from", "to", "amount"} and initial balances, process in order. Flag any transaction where the sender's balance would go negative. Return list of flagged transaction indices.
from collections importdefaultdictdefdetect_double_spend(initial_balances, transactions):
balances = defaultdict(int, initial_balances)
flagged = []
for i, txn inenumerate(transactions):
sender = txn["from"]
receiver = txn["to"]
amount = txn["amount"]
if balances[sender] < amount:
flagged.append(i)
else:
balances[sender] -= amount
balances[receiver] += amount
return flagged
Initialize balances with defaultdict(int, initial_balances). For each transaction, check if the sender can afford it before deducting. Flagged transactions are skipped (not applied). Core ledger integrity pattern.
P 70RobinhoodCoding ProblemHard
Order Book Matching Engine
Given a stream of buy/sell orders (order_id, side, price, quantity), implement matching: buy orders match with the lowest-priced sell if buy_price >= sell_price. Partial fills allowed. Return executed trades.
Two heaps: max-heap for buys, min-heap for sells. After each order, match while best buy >= best sell; trade at sell price for min quantities; push back remainder.
P 71CitadelCoding ProblemMedium
Task Queue with Priority
Implement a task queue: add(task_id, priority), remove(task_id), execute_next() → task_id or None. Highest priority first. Tie-breaking: earlier-added tasks first.
Implement PaymentProcessor with process(payment_id, amount, payment_fn). Retry on failure up to max_retries with exponential backoff (1s, 2s, 4s...). Same payment_id must never charge twice. Return {"status", "attempts"}.
Example
processor = PaymentProcessor(max_retries=3)
# second call with same payment_id → {"status": "already_processed", "attempts": 0}
Idempotency via a set of processed IDs checked before attempts. Exponential backoff on PaymentError. Mark success immediately; failed final attempt does not mark processed.
P 73RobinhoodCoding ProblemMedium
Leaderboard with Reset
Implement Leaderboard: add_score(player_id, score) adds to total, top(k) returns sum of top K scores, reset(player_id) resets to 0.
heapq.nlargest(k, values) for sum of top k scores without full sort.
Search, pricing & delivery
P 74DoorDashCoding ProblemEasy
Find Nearby Restaurants with Filtering
Given restaurants {"name", "rating", "distance"} and filters min_rating, max_distance, return matching restaurants sorted by distance ascending, then rating descending.
list comprehension filtermulti-key sortedtuple sort key
Solution
deffind_nearby(restaurants, min_rating, max_distance):
filtered = [
r for r in restaurants
if r["rating"] >= min_rating and r["distance"] <= max_distance
]
returnsorted(filtered, key=lambda r: (r["distance"], -r["rating"]))
Filter with a list comprehension, then sort with tuple key (distance, -rating). Ascending distance first; negating rating gives descending order within the same distance.
P 75Uber-styleCoding ProblemMedium
Ride Fare Calculator with Surge
Given ride details and surge pricing config per zone, calculate fare. Base formula: base_fare + distance * per_km + duration * per_min. Apply surge multiplier if ride starts during peak hours.
Lexicographic string compare works for HH:MM. Look up zone config; apply surge inside peak window; round(..., 2).
P 76Bloomberg-styleCoding ProblemMedium
Changelog Merger from Two Streams
Given two streams of change events {"record_id", "field", "new_value", "timestamp"}, merge into a unified view per record. For conflicts (same record, same field, same timestamp), stream A wins.
Example
At equal timestamps, A's value must overwrite B's when both touch the same field.
merge sort of two streamsconflict resolutiondict accumulation
Solution
defmerge_changelogs(stream_a, stream_b):
tagged = [(e["timestamp"], 1, e) for e in stream_a] # A has higher sort priority
tagged += [(e["timestamp"], 0, e) for e in stream_b] # B processed first
tagged.sort() # same timestamp: B (0) before A (1) → A overwrites
records = {}
for _, _, event in tagged:
rid = event["record_id"]
records.setdefault(rid, {})[event["field"]] = event["new_value"]
return records
Tag A with priority 1, B with 0. Sort by (timestamp, priority) so B applies first at ties; later assignment from A wins.
P 77DoorDash-styleCoding ProblemMedium
Delivery Time Estimator
Given historical delivery data [{"distance", "prep_time", "actual_time"}], build a simple estimator. For a new order with distance and prep_time, estimate delivery time using weighted average of the K most similar historical orders (by Euclidean distance in feature space).
Example
estimate(history, distance=2.5, prep_time=12, k=2) → weighted avg of nearest neighbors
Implement a text editor: insert(chars) appends to end, delete(k) removes up to k chars from end, get() returns current text, undo() undoes last op, redo() redoes last undone. New operations clear redo stack.
Snapshot the entire text before each mutation. undo swaps current text with the top of undo_stack (pushing current to redo). redo reverses. _save() clears the redo stack — critical so new work after undo invalidates redo history.
P 79Overmind-styleCoding ProblemHard
PII Redactor with Overlapping Spans
Given text and a list of PII entities {"start_offset", "end_offset", "type"} that may overlap, resolve overlaps (keep longer span when two entities share characters), then redact right-to-left. Return (redacted_text, pii_count).
Example
text = "Alice called Bob. ..."
entities = [ {...}, ... ]
→ ("[FULL_NAME]. [NAME]'s email is [EMAIL_ADDRESS].", {"FULL_NAME":1, ...})
from collections importCounterdefresolve_overlaps(entities):
# Sort by start ascending, then by span length descending (longer first)
sorted_ents = sorted(entities, key=lambda e: (e["start_offset"], -(e["end_offset"] - e["start_offset"])))
resolved = []
for entity in sorted_ents:
ifnot resolved:
resolved.append(entity)
continue
last = resolved[-1]
# If current entity starts within the previous one, skip it (keep longer)if entity["start_offset"] < last["end_offset"]:
continue
resolved.append(entity)
return resolved
defredact_pii(text, entities):
clean = resolve_overlaps(entities)
count = Counter(e["type"] for e in clean)
# Apply right-to-left to preserve offsetsfor entity insorted(clean, key=lambda e: e["start_offset"], reverse=True):
s = entity["start_offset"]
e = entity["end_offset"]
t = entity["type"]
text = text[:s] + f"[{t}]" + text[e:]
return text, dict(count)
Sort by start, prefer longer spans; skip overlapping smaller spans. Replace from right to left so indices stay valid. Count types with Counter.
P 80Samsara-styleCoding ProblemHard
Text Justification
Given a list of words and a max width, format text so each line has exactly maxWidth characters, fully justified. Extra spaces distributed left-to-right. Last line is left-justified.
Example
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16 → list of justified lines
greedy line packingspace distributionmodular arithmetic
Solution
deffull_justify(words, maxWidth):
result = []
i = 0while i < len(words):
# Pack as many words as possible into current line
line_len = len(words[i])
j = i + 1while j < len(words) and line_len + 1 + len(words[j]) <= maxWidth:
line_len += 1 + len(words[j])
j += 1
line_words = words[i:j]
num_words = len(line_words)
# Last line or single word: left-justifyif j == len(words) or num_words == 1:
line = " ".join(line_words)
result.append(line + " " * (maxWidth - len(line)))
else:
# Distribute spaces evenly
total_spaces = maxWidth - sum(len(w) for w in line_words)
gaps = num_words - 1
base_space = total_spaces // gaps
extra = total_spaces % gaps
line = ""for k, word inenumerate(line_words):
line += word
if k < gaps:
line += " " * (base_space + (1if k < extra else0))
result.append(line)
i = j
return result
Greedy packing per line; full justify by distributing extra spaces across gaps; last line padded on the right.
P 81Overmind-styleCoding ProblemMedium
Template String Processor
Given a template with {{variable}} placeholders and a context dict, resolve placeholders. Support nested resolution. Missing keys stay as-is. Max depth prevents infinite loops. Return (resolved_text, unresolved_count).
Example
template = "Dear {{title}} {{name}}, order {{order_id}} is {{status}}."
context = {"title": "Mr.", "name": "Smith", "order_id": "ORD-123"}
→ ("Dear Mr. Smith, order ORD-123 is {{status}}.", 1)
re.sub or manual parsingrecursive resolutioncycle detection
Solution
import re
defresolve_template(template, context, max_depth=5):
for _ inrange(max_depth):
defreplacer(match):
key = match.group(1)
if key in context:
returnstr(context[key])
return match.group(0) # leave as-is
new_text = re.sub(r'\{\{(\w+)\}\}', replacer, template)
if new_text == template:
break
template = new_text
unresolved = len(re.findall(r'\{\{(\w+)\}\}', template))
return template, unresolved
Iterative passes up to max_depth; replace known keys; count remaining {{...}} patterns.
Graphs, crawlers & messaging
P 82AnthropicCoding ProblemHard
Multi-Threaded Web Crawler with Dedup
Implement a crawler: crawl(seed_url, fetch_fn, max_depth) returns all unique URLs reachable from seed. Use BFS. Deduplicate URLs (strip # fragments, normalize trailing slashes).
Example
mock_fetch returns link lists per URL
crawl("https://a.com", mock_fetch, max_depth=2)
→ {"https://a.com", "https://a.com/about", "https://b.com"}
BFS with dequeURL normalizationset for visiteddepth tracking