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

41 Views
No Comment

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

题目一:内存数据库 详解

Level 1 — 基础 KV 操作

每条 Record 通过唯一字符串 key 访问,内含多个 field-value 对。

manipulate Illustrate Return Value
SET <key> <field> <value> 插入或覆盖字段值,记录不存在则创建 ""
GET <key> <field> 获取字段值,不存在返回空 值 或 ""
DELETE <key> <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 — 前缀筛选展示

新增扫描操作,结果格式为 field1(value1), field2(value2), ...,字段必须按字典序排列.

manipulate Illustrate
SCAN <key> 返回所有字段(字典序)
SCAN_BY_PREFIX <key> <prefix> 返回以 prefix 开头的字段(字典序)

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   → ""

格式细节:末尾不能有多余的 , ,建议先 sort,再 join,最后 trim。

Level 3 — TTL 存活时间

所有操作新增 _AT 后缀版本,带时间戳参数。字段有效区间为 [timestamp, timestamp + ttl),过期自动失效。

manipulate Illustrate
SET_AT <key> <field> <value> <timestamp> 带时间戳写入,永久有效
SET_AT_WITH_TTL <key> <field> <value> <timestamp> <ttl> 带 TTL 写入,超时失效
GET_AT <key> <field> <timestamp> 按时间戳读取(过期返回 ""
DELETE_AT <key> <field> <timestamp> 带时间戳删除
SCAN_AT <key> <timestamp> 扫描指定时刻存活的字段
SCAN_BY_PREFIX_AT <key> <prefix> <timestamp> 带前缀过滤的时间戳扫描

Example 1:

SET_AT_WITH_TTL A BC E 1 9    → ""  // BC 在 ts=10 过期
SET_AT_WITH_TTL A BC E 5 10   → ""  // 覆盖,BC 在 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 已过期

Example 2:

SET_AT A B C 1
SET_AT_WITH_TTL X Y Z 2 15    // Y 在 ts=17 过期
GET_AT X Y 3                  → "Z"
SET_AT_WITH_TTL A D E 4 10    // D 在 ts=14 过期
SCAN_AT A 13                  → "B(C), D(E)"
SCAN_AT X 16                  → "Y(Z)"
SCAN_AT X 17                  → ""        // Y 已过期
DELETE_AT X Y 20              → "false"   // X 所有字段均已过期

核心数据结构设计

// 字段值的版本单元
struct Val {
    string value;    // 实际值
    int timestamp;   // 写入时间戳
    int ttl;         // 0 = 永久有效
};

// 主结构:key → field → [历史版本]
unordered_map<string,
    unordered_map<string,
        vector<Val>>> db_;

// TTL 有效性判断(关键 helper)
auto isAlive = [&](Val& v, int ts) {
    if (v.ttl == 0) return true;       // 永久有效
    return ts < v.timestamp + v.ttl;   // 左闭右开区间
};

高频 Bug:有效区间是左闭右开 [ts, ts+ttl),判断用 ts < timestamp + ttl,写成 <= 会导致边界 case 全错。

Level 4 — 备份与恢复

支持在指定时间点创建数据库快照,并按需恢复,完整保留字段的 TTL 状态。

BACKUP <timestamp>   // 创建快照
RESTORE <timestamp>  // 恢复到指定快照

题目二:银行系统 详解

第二道题是另一个高频考点,题目背景是实现简化版银行后台。每个模块独立不难,但组合后状态管理的复杂度会显著上升。

各 Level 功能模块

Level functionality 核心操作
Level 1 账户创建 & 存款 CREATE_ACCOUNT · DEPOSIT
Level Two 转账 & 付款 TRANSFER · PAY
Level Three Merge accounts MERGE_ACCOUNTS
Level 4 Cashback GET_CASHBACK · TOP_SPENDERS

难点:模块组合后的状态爆炸

每个模块单独实现都属于中等难度,但当合并账户遇上 Cashback 时,问题变得棘手——合并后的账户应该如何继承原有的 Cashback 记录?转账历史如何保持一致性?

建议从 Level 2 就提前规划好交易记录的数据结构,避免到 Level 4 时大规模重构。

推荐数据结构

@dataclass
class Transaction:
    tx_id: str
    amount: float
    timestamp: int
    cashback_rate: float   # 0.0 表示无 cashback,Level 4 用
    cashback_settled: bool

@dataclass
class Account:
    balance: float
    transactions: list[Transaction]  # 提前设计,后续扩展用
    cashback_pending: float          # Level 4 新增

# MERGE 操作核心
def merge_accounts(src: Account, dst: Account):
    dst.balance += src.balance
    dst.transactions += src.transactions   # 历史记录合并
    dst.cashback_pending += src.cashback_pending
    delete_account(src)

时间分配参考

Level 建议用时 Difficulty Note
Level 1 ~15 min ⭐⭐⭐⭐⭐⭐⭐ 打好数据结构基础
Level Two ~20 min ⭐⭐⭐⭐⭐⭐⭐⭐ 格式细节容易掉分
Level Three ~30 min ⭐⭐⭐⭐⭐ TTL 逻辑最耗时
Level 4 ~25 min ⭐⭐⭐⭐ 备份 / Cashback 状态管理

两道题若在同一场考试出现,需灵活调整,优先保证高分 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, timestamp) The helper function is unified and reused.

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 Versioning is allowed, but the original unversioned operations must still function properly. The test cases are clearly stated not to be mixed, but your code should support both sets of interfaces simultaneously.

Language Selection Recommendation

Recommend Python:none: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 libraryHashMapNone providedTreeMap 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.

Program Assistance This service is long-term available:

  • Online Written Assessment Tool (HackerRank / CodeSignal / NovaCi and others)
  • coding test case debug 支持
  • VO 面试实时思路提示
  • 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 Senior Software Engineer at Amazon
Senior Engineer at Amazon, specializing in the development of core systems within infrastructure, with extensive practical experience in system scalability, reliability, and cost optimization. Currently focused on FAANG SDE interview preparation, assisting over 30 candidates in securing L5/L6 offers within a year.
END
 0