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 56 Stripe Coding Problem Medium
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.
Example
csv = """name, age, score Alice, 30, 85 Bob, 25, 92 Charlie, 35, 78""" process_csv(csv, "max", "age") → 35 process_csv(csv, "avg", "score") → 85.0 process_csv(csv, "sort", "score") → CSV string sorted by score desc
csv.DictReaderio.StringIOsorted + lambdasum/len for avgstr.strip
Solution
import csv from io import StringIO from typing import Union def process_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": return int(max(values)) if values else 0 elif operation == "min": return int(min(values)) if values else 0 elif operation == "avg": return round(sum(values) / len(values), 1) if values else 0.0 elif 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 57 Samsara Coding Problem Medium
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.'
string scanningindex-based parsingstate machineno regex constraint
Solution
def parse_links(text): result = [] i = 0 while 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 += 1 continue # 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 + 2 continue result.append(text[i]) i += 1 else: result.append(text[i]) i += 1 return ''.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 58 Airbnb Coding Problem Medium
CSV Slicer
Given a CSV string, extract specified rows and columns. Handle out-of-bounds gracefully (skip them). Return list of dicts.
Example
csv = """name,age,city Alice,30,NYC Bob,25,LA Charlie,35,Chicago""" csv_slicer(csv, rows=[0,2], columns=["name","city"]) → [{"name":"Alice","city":"NYC"}, {"name":"Charlie","city":"Chicago"}]
csv.DictReaderio.StringIOindex bounds checkingselective field extraction
Solution
import csv from io import StringIO def csv_slicer(csv_text, rows, columns): reader = csv.DictReader(StringIO(csv_text)) all_rows = list(reader) result = [] for row_idx in rows: if row_idx < 0 or 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 59 Notion-style Coding Problem Medium
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.
Example
parse_md_table(md) → [{"Name":"Alice","Age":"30","City":"NYC"}, ...]
str.splitlinesstr.split('|')str.stripalignment row detection
Solution
def parse_md_table(md_text): lines = [l.strip() for l in md_text.strip().splitlines() if l.strip()] if len(lines) < 2: return [] def parse_row(line): cells = [c.strip() for c in line.split('|')] return [c for c in cells if c] # remove empty strings from leading/trailing | def is_separator(line): cells = parse_row(line) return all(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 60 Perplexity-style Coding Problem Medium
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
Solution
import json import re from collections import Counter def normalize_message(msg): # Replace IPs, numbers, UUIDs, hex strings with * msg = re.sub(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', '*', msg) # IPs msg = re.sub(r'\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b', '*', msg) # UUIDs msg = re.sub(r'\b[a-f0-9]{6,}\b', '*', msg) # hex strings msg = re.sub(r'\b\d+\b', '*', msg) # numbers return msg def cluster_errors(error_lines, top_n): patterns = Counter() for line in error_lines: line = line.strip() if not line: continue try: entry = json.loads(line) except json.JSONDecodeError: continue msg = entry.get("message", "") normalized = normalize_message(msg) patterns[normalized] += 1 return patterns.most_common(top_n)
Normalize in order: IPs, UUIDs, hex, then bare numbers. Counter.most_common(n) returns top patterns.
Logs, time windows & streams
P 61 Anthropic Coding Problem Hard
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}
stack-based simulationstring splitstateful trackingnested call handling
Solution
from collections import defaultdict def exclusive_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 + 1 if stack: # Resume parent: set its start to after this function ended top_id, _ = stack[-1] stack[-1] = (top_id, timestamp + 1) return dict(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 62 Datadog Coding Problem Hard
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]}.
Example
store = LogStore() store.ingest("log1", "2025-01-16T23:09:51Z") store.ingest("log2", "2025-01-16T23:09:55Z") store.ingest("log3", "2025-01-16T23:15:00Z") store.query("2025-01-16T23:09:00Z", "2025-01-16T23:10:00Z", "MINUTE") → {"2025-01-16T23:09": ["log1", "log2"]}
bisect for range queriesISO timestamp truncationdefaultdict(list)string slicing
Solution
from collections import defaultdict from bisect import insort, bisect_left, bisect_right GRANULARITY_SLICES = { "YEAR": 4, "MONTH": 7, "DAY": 10, "HOUR": 13, "MINUTE": 16, "SECOND": 19, } class LogStore: def __init__(self): self.logs = [] # sorted list of (timestamp, log_id) def ingest(self, log_id, timestamp): insort(self.logs, (timestamp, log_id)) def query(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 in range(left, right): ts, log_id = self.logs[i] bucket_key = ts[:slice_len] buckets[bucket_key].append(log_id) return dict(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 63 Google Coding Problem Hard
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)].
Example
events = [(1, 0, "Start"), (2, 1, "Start"), (1, 3, "End"), (3, 4, "Start")] timeout = 5 → [(2, 6), (3, 9)]
dict with insertion orderingsliding expiry checkO(n) solution
Solution
def detect_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 time for rid, start_ts in active.items(): timed_out.append((rid, start_ts + timeout)) return sorted(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 64 Coinbase Coding Problem Easy
Log Keyword Extractor
Given multiline log text and a list of keywords, extract all lines containing ANY keyword (case-insensitive). Return {keyword: [matching_lines]}.
Example
logs = """2025-01-16 ERROR: Connection timeout 2025-01-16 INFO: User login 2025-01-16 ERROR: Database refused""" keywords = ["error", "database"] → {"error": [lines...], "database": [lines...]}
str.splitlinesstr.lowerdefaultdict(list)case-insensitive search
Solution
from collections import defaultdict def extract_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) return dict(result)
For each line, check each keyword with in on the lowercased line. A line can match multiple keywords.
P 65 Bloomberg Coding Problem Hard
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 import defaultdict def process_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 not in required_enrichers: continue if doc_id not in documents: documents[doc_id] = {"first_ts": ts, "enrichments": {}} documents[doc_id]["enrichments"][enricher] = enrichment # Check if all enrichers are present → emit immediately if set(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 out for 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 66 Perplexity-style Coding Problem Medium
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 &gt; 1800s starts a new session per user.
defaultdict(list)sorted by timestampgap detectionsession boundary
Solution
from collections import defaultdict SESSION_TIMEOUT = 1800 def reconstruct_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 67 Datadog Coding Problem Medium
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!!"]
buffer managementstring slicingstate machine (open/closed)
Solution
class BufferedWriter: def __init__(self, write_fn, buffer_size): self.write_fn = write_fn self.buffer_size = buffer_size self.buffer = "" self.closed = False def write(self, data): if self.closed: raise IOError("Writer is closed") self.buffer += data while len(self.buffer) >= self.buffer_size: chunk = self.buffer[:self.buffer_size] self.write_fn(chunk) self.buffer = self.buffer[self.buffer_size:] def flush(self): if self.buffer: self.write_fn(self.buffer) self.buffer = "" def close(self): self.flush() self.closed = True
Buffer as string; while loop emits fixed-size chunks. close flips closed flag.
P 68 Datadog-style Coding Problem Medium
Rolling Window Metrics
Implement MetricsWindow: record(metric, value, timestamp) stores a data point. query(metric, timestamp, window) returns {count, sum, avg, min, max} for entries in [timestamp - window, timestamp].
Example
m.query("latency", 3, 2) # window [1, 3] → {"count": 3, "sum": 450, "avg": 150.0, "min": 100, "max": 200}
defaultdict(list)bisect for range queriessorted insertion
Solution
from collections import defaultdict from bisect import insort, bisect_left, bisect_right class MetricsWindow: def __init__(self): self.data = defaultdict(list) # metric → [(timestamp, value)] def record(self, metric, value, timestamp): insort(self.data[metric], (timestamp, value)) def query(self, metric, timestamp, window): entries = self.data.get(metric, []) start = timestamp - window left = bisect_left(entries, (start,)) right = bisect_right(entries, (timestamp, float('inf'))) values = [v for _, v in entries[left:right]] if not values: return {"count": 0, "sum": 0, "avg": 0.0, "min": 0, "max": 0} return { "count": len(values), "sum": sum(values), "avg": round(sum(values) / len(values), 1), "min": min(values), "max": max(values), }
Sorted (timestamp, value) lists per metric; bisect for window slice; aggregate stats.
Ledgers, trading & payments
P 69 Coinbase Coding Problem Medium
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.
Example
balances = {"alice": 100, "bob": 50} txns = [ {"from": "alice", "to": "bob", "amount": 60}, {"from": "alice", "to": "bob", "amount": 50}, {"from": "bob", "to": "alice", "amount": 30}, ] → [1]
dict mutationbalance trackingedge cases (unknown accounts)
Solution
from collections import defaultdict def detect_double_spend(initial_balances, transactions): balances = defaultdict(int, initial_balances) flagged = [] for i, txn in enumerate(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 70 Robinhood Coding Problem Hard
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.
Example
orders = [("B1","BUY",100,10), ("S1","SELL",95,5), ("S2","SELL",98,8)] → [("B1","S1",95,5), ("B1","S2",98,5)]
heapq for price-prioritypartial fill trackingtwo-sided book
Solution
import heapq def match_orders(orders): buys = [] # max-heap (negate price): (-price, order_idx, order_id, remaining_qty) sells = [] # min-heap: (price, order_idx, order_id, remaining_qty) trades = [] for idx, (order_id, side, price, qty) in enumerate(orders): if side == "BUY": heapq.heappush(buys, (-price, idx, order_id, qty)) else: heapq.heappush(sells, (price, idx, order_id, qty)) # Try to match while buys and sells: neg_bp, bi, bid, bqty = buys[0] sp, si, sid, sqty = sells[0] buy_price = -neg_bp if buy_price < sp: break # no match possible fill_qty = min(bqty, sqty) trades.append((bid, sid, sp, fill_qty)) bqty -= fill_qty sqty -= fill_qty heapq.heappop(buys) heapq.heappop(sells) if bqty > 0: heapq.heappush(buys, (-buy_price, bi, bid, bqty)) if sqty > 0: heapq.heappush(sells, (sp, si, sid, sqty)) return 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 71 Citadel Coding Problem Medium
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.
Example
q = TaskQueue() q.add("email", 2) q.add("backup", 5) q.add("log", 2) q.execute_next() → "backup" q.execute_next() → "email"
heapqlazy deletionsequence counter for tie-breaking
Solution
import heapq class TaskQueue: def __init__(self): self.heap = [] # (-priority, seq, task_id) self.removed = set() # set of removed task_ids self.seq = 0 def add(self, task_id, priority): heapq.heappush(self.heap, (-priority, self.seq, task_id)) self.seq += 1 def remove(self, task_id): self.removed.add(task_id) def execute_next(self): while self.heap: neg_pri, seq, task_id = heapq.heappop(self.heap) if task_id not in self.removed: return task_id return None
Min-heap with negated priorities; sequence counter breaks ties. Lazy deletion avoids O(n) heap removal.
P 72 Stripe Coding Problem Medium
Payment Retry with Idempotency
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}
exponential backoffidempotency key trackingtry/except retry loop
Solution
import time class PaymentError(Exception): pass class PaymentProcessor: def __init__(self, max_retries=3): self.max_retries = max_retries self.processed = set() # idempotency: track processed payment IDs def process(self, payment_id, amount, payment_fn): if payment_id in self.processed: return {"status": "already_processed", "attempts": 0} wait = 1 for attempt in range(1, self.max_retries + 1): try: payment_fn(payment_id, amount) self.processed.add(payment_id) return {"status": "success", "attempts": attempt} except PaymentError: if attempt < self.max_retries: time.sleep(wait) wait *= 2 # exponential backoff return {"status": "failed", "attempts": self.max_retries}
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 73 Robinhood Coding Problem Medium
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.
Example
lb = Leaderboard() lb.add_score("alice", 50) lb.add_score("bob", 30) lb.add_score("alice", 20) lb.top(1) → 70 lb.reset("alice") lb.top(1) → 30
defaultdict(int)heapq.nlargestdict operations
Solution
from collections import defaultdict import heapq class Leaderboard: def __init__(self): self.scores = defaultdict(int) def add_score(self, player_id, score): self.scores[player_id] += score def top(self, k): return sum(heapq.nlargest(k, self.scores.values())) def reset(self, player_id): self.scores[player_id] = 0
heapq.nlargest(k, values) for sum of top k scores without full sort.
Search, pricing & delivery
P 74 DoorDash Coding Problem Easy
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.
Example
restaurants = [ {"name": "Sushi Place", "rating": 4.5, "distance": 2.1}, {"name": "Pizza Hub", "rating": 3.8, "distance": 1.5}, {"name": "Burger Joint", "rating": 4.7, "distance": 0.8}, ] find_nearby(restaurants, min_rating=4.0, max_distance=3.0) → [{"name": "Burger Joint",...}, {"name": "Sushi Place",...}]
list comprehension filtermulti-key sortedtuple sort key
Solution
def find_nearby(restaurants, min_rating, max_distance): filtered = [ r for r in restaurants if r["rating"] >= min_rating and r["distance"] <= max_distance ] return sorted(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 75 Uber-style Coding Problem Medium
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.
Example
config = {"downtown": {"peak_hours": [("17:00","20:00")], "surge": 1.8}} ride = {"distance_km": 5.2, "duration_min": 12, "start_time": "18:30", "zone": "downtown"} # fare = (2.50 + 5.2*1.20 + 12*0.30) * 1.8
time comparison as stringsconfig lookuparithmeticrounding
Solution
BASE_FARE = 2.50 PER_KM = 1.20 PER_MIN = 0.30 def calculate_fare(ride, config): distance = ride["distance_km"] duration = ride["duration_min"] start = ride["start_time"] zone = ride["zone"] raw_fare = BASE_FARE + distance * PER_KM + duration * PER_MIN # Check surge pricing multiplier = 1.0 zone_config = config.get(zone, {}) for peak_start, peak_end in zone_config.get("peak_hours", []): if peak_start <= start <= peak_end: multiplier = zone_config.get("surge", 1.0) break return round(raw_fare * multiplier, 2)
Lexicographic string compare works for HH:MM. Look up zone config; apply surge inside peak window; round(..., 2).
P 76 Bloomberg-style Coding Problem Medium
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
def merge_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 77 DoorDash-style Coding Problem Medium
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
Euclidean distanceheapq.nsmallestweighted averagefeature normalization
Solution
import heapq import math def estimate_delivery(history, distance, prep_time, k): # Calculate similarity to each historical order scored = [] for order in history: dist = math.sqrt( (order["distance"] - distance) ** 2 + (order["prep_time"] - prep_time) ** 2 ) scored.append((dist, order["actual_time"])) # Get K nearest nearest = heapq.nsmallest(k, scored) if not nearest: return 0.0 # Weighted average: closer orders get more weight (inverse distance) total_weight = 0 weighted_sum = 0 for dist, actual in nearest: weight = 1 / (dist + 0.001) # avoid division by zero weighted_sum += weight * actual total_weight += weight return round(weighted_sum / total_weight, 1)
KNN in 2D feature space; inverse-distance weighting; + 0.001 avoids div-by-zero.
Text, editors, templates & redaction
P 78 Notion Coding Problem Medium
Text Editor with Undo/Redo
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.
Example
editor = TextEditor() editor.insert("hello") editor.insert(" world") editor.get() → "hello world" editor.delete(6) editor.get() → "hello" editor.undo() editor.get() → "hello world" editor.redo() editor.get() → "hello"
command patternundo/redo stacksstate snapshots vs operation log
Solution
class TextEditor: def __init__(self): self.text = "" self.undo_stack = [] # stores previous states self.redo_stack = [] def _save(self): self.undo_stack.append(self.text) self.redo_stack.clear() # new op clears redo def insert(self, chars): self._save() self.text += chars def delete(self, k): self._save() self.text = self.text[:max(0, len(self.text) - k)] def get(self): return self.text def undo(self): if self.undo_stack: self.redo_stack.append(self.text) self.text = self.undo_stack.pop() def redo(self): if self.redo_stack: self.undo_stack.append(self.text) self.text = self.redo_stack.pop()
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 79 Overmind-style Coding Problem Hard
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, ...})
interval merginggreedy overlap resolutionright-to-left replacementCounter
Solution
from collections import Counter def resolve_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: if not 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 def redact_pii(text, entities): clean = resolve_overlaps(entities) count = Counter(e["type"] for e in clean) # Apply right-to-left to preserve offsets for entity in sorted(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 80 Samsara-style Coding Problem Hard
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
def full_justify(words, maxWidth): result = [] i = 0 while i < len(words): # Pack as many words as possible into current line line_len = len(words[i]) j = i + 1 while 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-justify if 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 in enumerate(line_words): line += word if k < gaps: line += " " * (base_space + (1 if k < extra else 0)) 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 81 Overmind-style Coding Problem Medium
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 def resolve_template(template, context, max_depth=5): for _ in range(max_depth): def replacer(match): key = match.group(1) if key in context: return str(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 82 Anthropic Coding Problem Hard
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
Solution
from collections import deque from urllib.parse import urldefrag def normalize_url(url): url, _ = urldefrag(url) # remove #fragment return url.rstrip("/") # remove trailing slash def crawl(seed_url, fetch_fn, max_depth): seed = normalize_url(seed_url) visited = {seed} queue = deque([(seed, 0)]) # (url, depth) while queue: url, depth = queue.popleft() if depth >= max_depth: continue try: links = fetch_fn(url) except Exception: continue for link in links: normalized = normalize_url(link) if normalized not in visited: visited.add(normalized) queue.append((normalized, depth + 1)) return visited
BFS with depth cap. urldefrag strips fragments; trailing slashes normalized. Visited set prevents cycles.
P 83 Palantir-style Coding Problem Hard
Graph with Shortest Path
Implement a Graph class: add_node(id), add_edge(from_id, to_id, weight), remove_node(id) (removes all edges), shortest_path(from_id, to_id) returns (distance, [path]).
Example
Dijkstra from A to C with multiple paths → optimal distance and path list.
adjacency listDijkstra's algorithmheapqpath reconstruction
Solution
import heapq from collections import defaultdict class Graph: def __init__(self): self.edges = defaultdict(dict) # node → {neighbor: weight} self.nodes = set() def add_node(self, node_id): self.nodes.add(node_id) def add_edge(self, from_id, to_id, weight): self.edges[from_id][to_id] = weight def remove_node(self, node_id): self.nodes.discard(node_id) del self.edges[node_id] for neighbors in self.edges.values(): neighbors.pop(node_id, None) def shortest_path(self, from_id, to_id): dist = {from_id: 0} prev = {} heap = [(0, from_id)] while heap: d, node = heapq.heappop(heap) if node == to_id: break if d > dist.get(node, float('inf')): continue for neighbor, weight in self.edges.get(node, {}).items(): new_dist = d + weight if new_dist < dist.get(neighbor, float('inf')): dist[neighbor] = new_dist prev[neighbor] = node heapq.heappush(heap, (new_dist, neighbor)) if to_id not in dist: return (float('inf'), []) # Reconstruct path path = [] node = to_id while node is not None: path.append(node) node = prev.get(node) return (dist[to_id], path[::-1])
Dijkstra with min-heap; prev for path; remove_node clears incoming and outgoing.
P 84 Slack-style Coding Problem Medium
Message Threading / Conversation Rebuilder
Given flat messages {"msg_id", "thread_id", "user", "text", "timestamp"}, reconstruct threads. Root message has msg_id == thread_id. Replies sorted by timestamp. Return threads sorted by most recent activity.
Example
Group by thread_id; sort messages; sort threads by last_activity desc.
defaultdict(list)grouping by thread_idsorting nested + outer
Solution
from collections import defaultdict def rebuild_threads(messages): threads = defaultdict(list) for msg in messages: threads[msg["thread_id"]].append(msg) result = [] for thread_id, msgs in threads.items(): msgs.sort(key=lambda m: m["timestamp"]) last_activity = msgs[-1]["timestamp"] result.append({ "root": thread_id, "messages": msgs, "last_activity": last_activity, }) result.sort(key=lambda t: t["last_activity"], reverse=True) return result
Group by thread_id, sort messages by time, compute last_activity, sort threads by recency.
← Category I: defaultdict Mastery ↑ All Categories