OpenAI 面试真题还原:Credits 系统设计与实现 – 一亩三分地 – 面试辅助 – VO help – VO support

这次要分享的是一道 OpenAI 面试真题,很多同学光看题目就觉得很棘手,但真实的面试场景里,其实难点不在代码本身,而在如何快速把问题拆解、思路讲清。下面我就带大家还原一次完整的面试辅助过程。

📌 题目原文
You’re building a system to track balances for the OpenAI API credit purchasing system.
API users can purchase credit grants, specified by an ID, that are active at a timestamp and that let them use the API. Unused credit grant balances expire at a certain time.

However, there’s a kink in our system: requests can arrive out of order because our system is built on a really unstable network. For example, a request to subtract credits can arrive at the system before the request to add credits, even though the request to add credits has a lower timestamp.

Your task is to implement the Credits class, which should support the following operations:

  • Granting credits, subtracting credits, and getting the credit balance for a user
  • The ability to handle requests that arrive out of order

Guidelines/hints:

  • Don’t worry about memory/performance concerns
  • All timestamps are ints and unique
  • Subtract from grants expiring soonest first

🧩 候选人第一反应
很多人读完会有点懵:

  • 要处理「乱序请求」
  • 还要考虑「过期时间」
  • 扣款顺序必须「先从最早过期的 credit 开始」

现场时间有限,如果慌了,可能连最基本的代码框架都没写出来。


💡 辅助思路
我们的做法是,先帮候选人把思路拆开:

  1. 数据结构:每次 create_grant 存储 (timestamp, expiration, amount)
  2. 乱序问题:无论请求什么时候到达,都用一个「时间轴」回放逻辑,保证计算结果一致。
  3. 过期处理:在 get_balance 或 subtract 时,把小于当前时间的过期 credit 清理掉。
  4. 扣款顺序:排序 grants,优先从快过期的减。

在面试现场,我们会逐字稿式地提示候选人该怎么说:“First, I’ll store each credit grant with its expiration. Then when subtracting, I’ll always consume from the earliest expiring grant. And before each operation, I’ll clean up expired ones.”

这样解释,就算代码没写完,也能拿到大部分思路分。


🖊 代码片段(示意)

class Credits:
    def create_grant(self, timestamp, grant_id, amount, expiration_timestamp):
        # store grant info
    
    def subtract(self, timestamp, amount):
        # remove expired, then subtract earliest expiring
    
    def get_balance(self, timestamp):
        # remove expired, return total

测试用例中,我们帮候选人写好了详细的断言,比如:

  • test_basic_subtraction():先扣再加,看能否正确计算
  • test_expiration():credit 到期后是否清零
  • test_many_grants():多批次扣款顺序是否正确

🎯 面试价值
这类题目考的不是花哨的数据结构,而是:

  • 你能不能 清晰沟通思路
  • 你是否会用 测试驱动 验证
  • 面试官能不能从你身上看到 工程化思维

很多同学卡在“想一步到位写完”,但其实只要你敢先写最简单的版本,再逐步完善(比如先写 create_grant + get_balance,再加 subtract),就能让面试官看到进展。


🔑 总结
OpenAI 的这道题典型地体现了“场景建模 + 边界处理”的考点。准备类似面试时,除了刷题,更要练习:

  • 如何解释「乱序请求」
  • 如何用「测试用例」自证正确
  • 如何在压力下逐步搭建可运行的代码框架

如果你也在准备大厂的BQ, 算法与系统设计面试,欢迎添加微信,即可领取北美面试求职通关秘诀。我们也有代面试,面试辅助,OA代写等服务助您早日上岸~

Leave a Reply

Your email address will not be published. Required fields are marked *