Anthropic SDE Interview | Detailed Explanation of Memory Database and Bank System (With Code)

1,283 Views

Anthropic SDE OA consists of 90 minutes and is divided into 4 levels. Each level can only be unlocked after successfully completing all unit tests in the previous levels. To progress to the next level, one must pass through all unit tests for each level. Two core questions are "Memory Database" (supporting TTL and backup/recovery) and "Bank System" (deposit/withdrawal/transfer plus Cashback). The questions themselves are not difficult; however, they involve multiple functional modules, tight time constraints, and need to be developed concurrently with modifications. Managing the rhythm and ensuring code modularity is key.

Anthropic SDE Interview | Detailed Explanation of Memory Database and Bank System (With Code)

Anthropic SDE OA Comprehensive Exam Structure

The OA rhythm is similar to the level-based coding challenges of CodeSignal. Each Level adds new features on top of the code from the previous level, so a good code structure needs to be designed at the outset in order for subsequent expansions to be smooth.

Level thematic Key challenge
Level 1 Fundamental Operations Establishing an extendible core data structure
Level Two Filter Display Dictionary order sorting + Strict output format
Level Three TTL (Time to Live) Lifespan Timeline Management + Expiration Boundary Logic
Level 4 Complete Persistent Snapshot Status Comprehensive Persistent Snapshot Status

Topic 1: Detailed explanation of in-memory database

Level 1 — Basic KV operations

Each Record passes a unique string key access, including multiple field-value right.

manipulate Illustrate Return Value
SET <key> <field> <value> Insert or overwrite field values, create the record if it does not exist ""
GET <key> <field> Get the field value, if it does not exist, return empty value or ""
DELETE <key> <field> Delete field "true" / "false"

Example:

SET A B E      → ""   // {"A": {"B": "E"}}
SET A C F      → ""   // {"A": {"B": "E", "C": "F"}}
GET A B        → "E"
GET A D        → ""
DELETE A B     → "true"
DELETE A D     → "false"

Level 2 — Prefix filtering display

Added a new scan operation, the result format is field1(value1), field2(value2), ..., fieldMust be sorted lexicographically.

manipulate Illustrate
SCAN <key> Return all fields (lexicographic order)
SCAN_BY_PREFIX <key> <prefix> Returns fields starting with prefix (lexicographic order)

Example:

SET A BC E       → ""
SET A BD F       → ""
SET A C G        → ""
SCAN_BY_PREFIX A B   → "BC(E), BD(F)"
SCAN A               → "BC(E), BD(F), C(G)"
SCAN_BY_PREFIX B B   → ""

Format details: There should be no redundant at the end , , it is recommended to sort first, then join, and finally trim.

Level 3 — TTL time to live

All operations added _AT Suffix version, with timestamp parameter. The valid range of the field is [timestamp, timestamp + ttl), it will automatically expire upon expiration.

manipulate Illustrate
SET_AT <key> <field> <value> <timestamp> Written with timestamp, permanently valid
SET_AT_WITH_TTL <key> <field> <value> <timestamp> <ttl> Write with TTL, expire after timeout
GET_AT <key> <field> <timestamp> Read by timestamp (return after expiration) ""
DELETE_AT <key> <field> <timestamp> Delete with timestamp
SCAN_AT <key> <timestamp> Scan the fields that are alive at a specified time
SCAN_BY_PREFIX_AT <key> <prefix> <timestamp> Timestamp scan with prefix filtering

Example 1:

SET_AT_WITH_TTL A BC E 1 9 → "" // BC expires at ts=10
SET_AT_WITH_TTL A BC E 5 10 → "" // Overwrite, BC expires at ts=15
SET_AT A BD F 5 → ""
SCAN_BY_PREFIX_AT A B 14 → "BC(E), BD(F)"
SCAN_BY_PREFIX_AT A B 15 → "BD(F)" // BC has expired

Example 2:

SET_AT A B C 1
SET_AT_WITH_TTL X Y Z 2 15 // Y expires at ts=17
GET_AT X Y 3 → "Z"
SET_AT_WITH_TTL A D E 4 10 // D expires at ts=14
SCAN_AT A 13 → "B(C), D(E)"
SCAN_AT X 16 → "Y(Z)"
SCAN_AT X 17 → "" // Y has expired
DELETE_AT X Y 20 → "false" // All fields of X have expired

Core data structure design

// Version unit of field value
struct Val {
    string value; //actual value
    int timestamp; // write timestamp
    int ttl; // 0 = valid forever
};

// Main structure: key → field → [historical version]
unordered_map<string,
    unordered_map<string,
        vector>> db_;

// TTL validity judgment (key helper)
auto isAlive = [&](Val& v, int ts) {
    if (v.ttl == 0) return true; // permanently valid
    return ts < v.timestamp + v.ttl; // Left closed and right open interval
};

High Frequency Bug: The valid range is left closed and right open [ts, ts+ttl), used for judgment ts < timestamp + ttl, written as <= Will cause all boundary cases to be wrong.

Level 4 — Backup and recovery

Supports creating database snapshots at specified points in time and restoring them on demand, fully retaining the TTL status of fields.

BACKUP  // Create snapshot
RESTORE  //Restore to the specified snapshot

Topic 2: Detailed explanation of banking system

The second question is another high-frequency test point. The background of the question is to implement a simplified version of the bank backend. It is not difficult for each module to be independent, but the complexity of state management will increase significantly after combination.

Each Level function module

Level functionality core operations
Level 1 Account creation & deposit CREATE_ACCOUNT · DEPOSIT
Level Two Transfers & Payments TRANSFER · PAY
Level Three Merge accounts MERGE_ACCOUNTS
Level 4 Cashback GET_CASHBACK · TOP_SPENDERS

Difficulty: state explosion after module combination

Each module is moderately difficult to implement individually, but when a merged account encounters Cashback, the problem becomes tricky - how should the merged account inherit the original Cashback record? How to maintain consistency in transfer history?

It is recommended to plan the data structure of transaction records in advance from Level 2 to avoid large-scale reconstruction at Level 4.

Recommended data structures

@dataclass
class Transaction:
    tx_id:str
    amount: float
    timestamp: int
    cashback_rate: float # 0.0 means no cashback, used for Level 4
    cashback_settled: bool

@dataclass
classAccount:
    balance: float
    transactions: list[Transaction] # Design in advance and use for subsequent expansion
    cashback_pending: float # Level 4 New

# MERGE operation core
def merge_accounts(src: Account, dst: Account):
    dst.balance += src.balance
    dst.transactions += src.transactions #History merge
    dst.cashback_pending += src.cashback_pending
    delete_account(src)

Time allocation reference

Level Recommended time Difficulty Note
Level 1 ~15 min ⭐⭐⭐⭐⭐⭐⭐ Lay a good foundation for data structure
Level Two ~20 min ⭐⭐⭐⭐⭐⭐⭐⭐ Format details are easy to lose points
Level Three ~30 min ⭐⭐⭐⭐⭐ TTL logic is the most time-consuming
Level 4 ~25 min ⭐⭐⭐⭐ Backup/Cashback state management

If two questions appear in the same exam, they must be adjusted flexibly to ensure that the one with the highest score passes the Level.

Preparation Tips & Avoiding Pitfalls Guide

Design first, then proceed.

Plan out the overall data structure when reaching Level 1. Otherwise, if the design is not scalable, Level 3 will require extensive restructuring, which won't have enough time.

The TTL boundary is the highest frequency bug.

Effective Range Is [timestamp, timestamp+ttl)Using ts < timestamp + ttl Assessment, do not write as <=Recommend encapsulating a isAlive(val, ts) Helper functions are reused uniformly.

The output format of SCAN must strictly match

The ending should not have any extra content. , Fields must be in dictionary order. Recommended approach: Sort first, then join, and finally trim the trailing characters.

Bank systems need to have interfaces reserved in advance for Cashback.

Starting from Level 2 Transaction Leave the cashback field reserved, even if it is not currently needed. Otherwise, Level 4 will need to revisit and modify everything. PAY Relevant logic.

Time allocation is a core competency.

Levels 3 and 4 have higher scores, with many getting stuck on the formatting details at Level 2. Suggested is to quickly progress from Levels 1/2 to Level 3 after mastering those levels, without striving for perfect code.

Attention to Backward Compatibility Requirements

Level 3 Added _AT version operation, but the original untimestamped operation still needs to work properly. The question clearly states that test cases will not be mixed, but your code must support both sets of interfaces.

Language selection suggestions

Recommend Python:Dictinary + Data class It is quick to implement, sort and process strings, has concise syntax for TTL (Time To Live) and cashback codes, suitable for time-constrained scenarios.

Alternative Java/C++If you are very familiar with the standard libraryHashMap,TreeMap However, string concatenation and formatting are more cumbersome and prone to `format` bugs compared to Python.

Summarize

The difficulty with Anthropic Open Access lies not in a single algorithm but in designing scalable systems within limited time, and iterating rapidly at each stage. When studying for it:

  1. Practicing Similar Hierarchical System Design Questions (in the CodeSignal Style)
  2. Proficient in string handling and sorting APIs for the used language
  3. Conduct a local simulated 90-minute timed practice session to feel the real rhythm.

If you have recently been intensively working on assessments from organizations like Anthropic, OpenAI, Databricks, Stripe, and TikTok and are worried about encountering tricky questions during the official assessment, running out of time to complete all tasks, or failing hidden tests, you can also seek assistance from professional teams in advance.

ProgramHelp This service is long-term available:

  • Online Written Assessment Tool (HackerRank / CodeSignal / NovaCi and others)
  • coding test case debug support
  • VO interview real-time thinking tips
  • Mock interview
  • SDE/Quant/DS Interview Coaching

The core advantage lies in the real-time assistance provided by North American CS engineering teams, as well as their familiarity with many高频OA题库, especially for system design-type questions. This often allows for faster identification of bugs and hidden cases.

If the goal is to be as steady as possible through the application process, preparing resources in advance will be much easier.

author avatar
Jory Wang Amazon Senior Software Development Engineer
Amazon senior engineer, focusing on the research and development of infrastructure core systems, with rich practical experience in system scalability, reliability and cost optimization. Currently focusing on FAANG SDE interview coaching, helping 30+ candidates successfully obtain L5/L6 Offers within one year.
END
 0