Anthropic software engineer interviews cover algorithms, data structures, system design, and coding problems drawn from real interview rounds.
Question Your task is to implement a simple in-memory cloud storage system that maps objects (files) to their metadata (name, size, etc.). You...
Input: Graph (nodes and edges)Question Design a banking system that supports account management, transactions, and various financial operations.
Input: Graph (nodes and edges)Description Sampling profilers capture the call stack at periodic intervals to analyze program performance. However, most trace visualization tools...
Input: ListDescription Given a list of file paths in a directory system, find all duplicate files. Two files are considered duplicates if they have identical...
Input: ListDescription Given a URL startUrl and an interface HtmlParser, implement a concurrent web crawler to discover all unique URLs that share the...
Description Implement a simplified in-memory database that supports record manipulation with various operations. The system should handle basic...
Input: Graph (nodes and edges)k workers (indexed 0 to k-1). Each worker holds an unsorted, roughly equal slice of the data....Input: Stringtext and a dictionary array where each element is in the format "<key>:<id>". Here key is a token string and id...Input: Arrayworkers and events are lists of maps with string keys and string values. A worker has worker_id, model, and capacity_tokens; model is a logical serving-pool name such as sonnet.start event has action, request_id, session_id, model, and tokens. Tokens represent a reservation held until a corresponding finish event, not a billing measurement.capacity_tokens. Equality is allowed.(session_id, model) if it is eligible. Otherwise, choose the eligible worker with the greatest remaining token capacity before admission; break ties by lexicographically smallest worker_id.{"request_id": ID, "status": "ACCEPTED", "worker_id": WORKER}. A rejected start changes no state and emits {"request_id": ID, "status": "REJECTED", "reasons": ["NO_CAPACITY"]}.finish event has only action and request_id. If that request is active, release its reservation and emit status RELEASED with its worker ID. Otherwise, emit {"request_id": ID, "status": "NOOP"}. Finishing a request does not clear its sticky assignment.route_requests(workers: list[dict[str, str]], events: list[dict[str, str]]). The return type is up to you; the examples show its required JSON representation as an ordered list of event results.{
"workers": [
{"worker_id": "w1", "model": "sonnet", "capacity_tokens": "10"},
{"worker_id": "w2", "model": "sonnet", "capacity_tokens": "8"}
],
"events": [
{"action": "start", "request_id": "r1", "session_id": "s1", "model": "sonnet", "tokens": "6"},
{"action": "start", "request_id": "r2", "session_id": "s1", "model": "sonnet", "tokens": "5"},
{"action": "start", "request_id": "r3", "session_id": "s2", "model": "sonnet", "tokens": "5"},
{"action": "finish", "request_id": "r1"},
{"action": "start", "request_id": "r4", "session_id": "s1", "model": "sonnet", "tokens": "3"}
]
}[
{"request_id": "r1", "status": "ACCEPTED", "worker_id": "w1"},
{"request_id": "r2", "status": "ACCEPTED", "worker_id": "w2"},
{"request_id": "r3", "status": "REJECTED", "reasons": ["NO_CAPACITY"]},
{"request_id": "r1", "status": "RELEASED", "worker_id": "w1"},
{"request_id": "r4", "status": "ACCEPTED", "worker_id": "w2"}
]r1 leaves 4 tokens available on w1. Its session's next request needs 5, so r2 falls back to w2, leaving 3 there. Neither worker can admit r3. After r1 finishes, w1 has 10 available, but r4 still chooses sticky worker w2, reaching exactly its capacity of 8.Part 2 — Overlapping hierarchical admission policiesquotas, another list of string-to-string maps. Each record has quota_id, limit_tokens, and parents. parents is a comma-separated list of quota IDs, or the empty string. The graph is a directed acyclic graph; a quota can have multiple parents.quota_ids, a comma-separated list of directly charged quota IDs, possibly empty. Charge each direct quota and every reachable ancestor exactly once per request, even if there are multiple paths or overlapping direct memberships.q, reject if current_usage[q] + tokens > limit_tokens[q]. Its reason is QUOTA:<quota_id>. Equality is allowed.NO_CAPACITY, with the complete reason list sorted lexicographically. Do not stop at the first violation.results, containing the ordered event results, and quota_usage, mapping every configured quota ID to its final integer usage, including zeros.route_requests_with_quotas(workers: list[dict[str, str]], events: list[dict[str, str]], quotas: list[dict[str, str]]). Discuss how the return type changes before implementing it. Structure admission policies so future policy types can be added without rewriting the routing loop; additional quota nodes and parent edges must remain data-driven.{
"workers": [
{"worker_id": "w1", "model": "sonnet", "capacity_tokens": "10"},
{"worker_id": "w2", "model": "sonnet", "capacity_tokens": "8"}
],
"quotas": [
{"quota_id": "org", "limit_tokens": "12", "parents": ""},
{"quota_id": "team", "limit_tokens": "8", "parents": "org"},
{"quota_id": "project", "limit_tokens": "7", "parents": "team,org"}
],
"events": [
{"action": "start", "request_id": "a", "session_id": "s1", "model": "sonnet", "tokens": "6", "quota_ids": "project,team"},
{"action": "start", "request_id": "b", "session_id": "s2", "model": "sonnet", "tokens": "3", "quota_ids": "team"},
{"action": "finish", "request_id": "a"},
{"action": "start", "request_id": "c", "session_id": "s2", "model": "sonnet", "tokens": "7", "quota_ids": "project"}
]
}{
"results": [
{"request_id": "a", "status": "ACCEPTED", "worker_id": "w1"},
{"request_id": "b", "status": "REJECTED", "reasons": ["QUOTA:team"]},
{"request_id": "a", "status": "RELEASED", "worker_id": "w1"},
{"request_id": "c", "status": "ACCEPTED", "worker_id": "w1"}
],
"quota_usage": {"org": 7, "project": 7, "team": 7}
}a charges project, team, and org once each, giving usages of 6, not 12 or 18. For b, a worker is available, but team usage would be 6 + 3 = 9 > 8; organization usage would be 9 <= 12, and project is not charged. Rejection leaves every usage at 6. Finishing a resets all three to zero; c then reserves 7, satisfying project 7 <= 7, team 7 <= 8, and organization 7 <= 12.Example 3:{
"workers": [
{"worker_id": "w1", "model": "sonnet", "capacity_tokens": "10"},
{"worker_id": "w2", "model": "sonnet", "capacity_tokens": "8"}
],
"quotas": [
{"quota_id": "org", "limit_tokens": "10", "parents": ""},
{"quota_id": "team", "limit_tokens": "6", "parents": "org"},
{"quota_id": "project", "limit_tokens": "6", "parents": "team,org"}
],
"events": [
{"action": "start", "request_id": "x", "session_id": "s1", "model": "sonnet", "tokens": "6", "quota_ids": "project"},
{"action": "start", "request_id": "y", "session_id": "s2", "model": "sonnet", "tokens": "9", "quota_ids": "project"},
{"action": "finish", "request_id": "y"},
{"action": "finish", "request_id": "x"},
{"action": "start", "request_id": "z", "session_id": "s1", "model": "sonnet", "tokens": "6", "quota_ids": "team,project"}
]
}{
"results": [
{"request_id": "x", "status": "ACCEPTED", "worker_id": "w1"},
{"request_id": "y", "status": "REJECTED", "reasons": ["NO_CAPACITY", "QUOTA:org", "QUOTA:project", "QUOTA:team"]},
{"request_id": "y", "status": "NOOP"},
{"request_id": "x", "status": "RELEASED", "worker_id": "w1"},
{"request_id": "z", "status": "ACCEPTED", "worker_id": "w1"}
],
"quota_usage": {"org": 6, "project": 6, "team": 6}
}x, workers have 4 and 8 tokens available and every quota has usage 6. Request y needs 9, so neither worker fits; each quota would reach 6 + 9 = 15, exceeding limits 10, 6, and 6. All four reasons must appear, and finishing rejected request y is a no-op. Finishing x releases 6 everywhere. Request z charges each node only once despite overlapping memberships, returning all three usages to exactly 6.Notes:class Bank: def __init__(self) -> None: def create_account(self, account_id: str) -> None: def deposit(self, account_id: str, amount: float) -> None: def withdraw(self, account_id: str, amount: float) -> bool: def transfer(self, from_account: str, to_account: str, amount: float) -> bool: bank = Bank() bank.create_account('123') bank.deposit('123', 200.0) bank.withdraw('123', 50.0) 150.0 (balance after the operations) bank.create_account('123') bank.create_account('456') bank.deposit('123', 300.0) bank.transfer('123', '456', 150.0) (True, 150.0) (Transfer was successful, remaining balance for 123 is 150.0) 1 ≤ account_id.length ≤ 100 amount ≥ 0 BankingSystem class that allows for concurrent deposits and withdrawals. The system must ensure thread-safety so that operations do not conflict. Implement the following methods in the class: deposit(accountId: int, amount: float) -> None: Increases the balance of the specified account by the given amount. withdraw(accountId: int, amount: float) -> bool: Decreases the balance by the specified amount if sufficient funds are available; returns True if successful, otherwise False. get_balance(accountId: int) -> float: Returns the current balance of the specified account. class BankingSystem: def deposit(accountId: int, amount: float) -> None def withdraw(accountId: int, amount: float) -> bool def get_balance(accountId: int) -> float bs = BankingSystem() bs.deposit(1, 500.0) bs.withdraw(1, 200.0) bs.get_balance(1)
300.0 bs.withdraw(1, 400.0)
False accountId ≤ 10000 amount ≤ 10000 Counter that counts the number of times a specific event occurs while ensuring thread safety. The increment method should increase the counter when an event happens, and the get method should return the current count. If a failure occurs while incrementing, the system should handle this gracefully without losing the count. Use a lock mechanism to ensure thread safety and implement recovery logic. def increment(self) -> None: def get(self) -> int: increment() called get() called n accounts with the most total transactions (both deposits and withdrawals). Function/class signature: class Bank: def create_account(self, account_id: int) -> None: def deposit(self, account_id: int, amount: float) -> None: def withdraw(self, account_id: int, amount: float) -> bool: def get_total_transactions(self, account_id: int) -> float: def get_top_accounts(self, n: int) -> List[int]: bank = Bank() bank.create_account(1) bank.deposit(1, 100) bank.withdraw(1, 50) bank.create_account(2) bank.deposit(2, 200) bank.deposit(2, 80) bank.get_top_accounts(1)
[2] 2 has the highest total transactions (280). Example 2: bank.create_account(3) bank.deposit(3, 150) bank.withdraw(3, 30) bank.get_top_accounts(2)
[2, 3] 2 has (280) and account 3 has (120) total transactions.Constraints: 1 <= account_id <= 10^4 0 <= amount <= 10^6 1 <= n <= 100 nums, return the maximum number of consecutive 1s in the array. For example, in the array [1,1,0,1,1,1], the longest consecutive sequence of 1s is 3. Your function should handle large inputs and provide results quickly, as this operation could be part of a larger data analysis framework.Function/class signature: def findMaxConsecutiveOnes(nums: List[int]) -> int:findMaxConsecutiveOnes([1,1,0,1,1,1]) 3 1s is 111.Example 2: findMaxConsecutiveOnes([1,0,1,1,0,1]) 2 1s is 11.Constraints: 1 <= nums.length <= 10^5 nums[i] is either 0 or 1. class BankingSystem:def create_account(self, account_id: int) -> None:def transfer(self, from_account: int, to_account: int, amount: float, schedule_time: datetime) -> bool:def get_balance(self, account_id: int) -> float:Example 1: create_account(1) create_account(2) transfer(1, 2, 100, datetime(2023, 10, 1, 10, 0)) True transfer(1, 2, 50, datetime(2023, 10, 1, 10, 0)) False Background
Requirements
end events for the old suffix, innermost first, followed by start events for the new suffix, outermost first. All events use the new sample's timestamp. A frame's depth is its zero-based position in its stack; repeated function names represent distinct recursive frames. Matching prefix frames are assumed to remain active: do not infer unobserved calls between samples.finish(thread_id, timestamp) closes the thread by ending every remaining frame, innermost first. Its timestamp must be at least the thread's latest sample timestamp. Finishing an already finished thread returns false without emitting events or checking the timestamp. Finishing an unknown thread raises ValueError; adding a sample to a finished thread also raises ValueError.drain_events() returns and removes all buffered events. Each event is an object with exactly thread_id, timestamp, kind, function, and depth. Preserve method-call order, not global timestamp order; within a call, preserve the nesting order defined above. A second drain without intervening events returns an empty list. Copy input stacks so later caller mutations cannot change stored state.Class API
StackTraceReconstructor() — create an empty reconstructor.add_sample(thread_id: str, timestamp: int, stack: list[str]) -> None — register or update a thread and append inferred events; raise ValueError for a finished thread or a non-increasing timestamp.finish(thread_id: str, timestamp: int) -> bool — return true when an active thread is closed, or false if already closed; raise ValueError for an unknown thread or a timestamp earlier than its latest sample.drain_events() -> list[dict[str, str | int]] — atomically return all pending events and clear the buffer.Example 1
[
{"method":"add_sample","args":["worker-1",10,["serve","decode"]]},
{"method":"add_sample","args":["worker-1",14,["serve","sample"]]},
{"method":"finish","args":["worker-1",20]},
{"method":"drain_events","args":[]}
][
null,
null,
true,
[
{"thread_id":"worker-1","timestamp":10,"kind":"start","function":"serve","depth":0},
{"thread_id":"worker-1","timestamp":10,"kind":"start","function":"decode","depth":1},
{"thread_id":"worker-1","timestamp":14,"kind":"end","function":"decode","depth":1},
{"thread_id":"worker-1","timestamp":14,"kind":"start","function":"sample","depth":1},
{"thread_id":"worker-1","timestamp":20,"kind":"end","function":"sample","depth":1},
{"thread_id":"worker-1","timestamp":20,"kind":"end","function":"serve","depth":0}
]
]["serve"], so only decode ends and sample starts. Finishing ends the two remaining frames in reverse depth order.Example 2
[
{"method":"add_sample","args":["A",5,["walk","walk"]]},
{"method":"add_sample","args":["B",2,[]]},
{"method":"add_sample","args":["A",6,["walk"]]},
{"method":"add_sample","args":["B",3,["serve"]]},
{"method":"finish","args":["A",6]},
{"method":"finish","args":["A",0]},
{"method":"drain_events","args":[]},
{"method":"drain_events","args":[]}
][
null,
null,
null,
null,
true,
false,
[
{"thread_id":"A","timestamp":5,"kind":"start","function":"walk","depth":0},
{"thread_id":"A","timestamp":5,"kind":"start","function":"walk","depth":1},
{"thread_id":"A","timestamp":6,"kind":"end","function":"walk","depth":1},
{"thread_id":"B","timestamp":3,"kind":"start","function":"serve","depth":0},
{"thread_id":"A","timestamp":6,"kind":"end","function":"walk","depth":0}
],
[]
]finish is a no-op even with an earlier timestamp.Constraints
[0, 10^12]; thread IDs and function names are nonempty strings of at most 128 characters. Types and these bounds are guaranteed by callers.set(file: str, data: bytes) -> None to store a file.get(file: str) -> Optional[bytes] to retrieve file data by name.filter(criteria: Callable[[str], bool]) -> List[str] to return a list of files matching certain conditions.backup(destination: str) -> None to backup all files to a specified location.restore(source: str) -> None to restore files from a backup location.Class API:set(file: str, data: bytes) -> None: Stores the file file with the content data in bytes.get(file: str) -> Optional[bytes]: Returns the content of the file if it exists, otherwise returns None.filter(criteria: Callable[[str], bool]) -> List[str]: Returns a list of file names that match the given criteria.backup(destination: str) -> None: Backs up the current files to the specified destination.restore(source: str) -> None: Restores files from a backup source.set('document.txt', b'This is a document.') set('image.png', b'Image data here.') get('document.txt') returns b'This is a document.' filter(lambda x: x.endswith('.png')) returns ['image.png'] set is used to store files and get retrieves the content of a specific file. The filter method uses a lambda function to find files with the .png extension.Example 2: backup('/backup/location') restore('/backup/location') Sign up for free to access walkthroughs, AI-generated questions, and more.
Get Started Free