Problem Description
Imagine an online hardware store that sells products of different sizes.
The store could sell small items like a mouse or larger items like a laptop.
These items cost a different amount to be shipped out.
Shipping to different countries can also cost a different amount.
Imagine you have an order object that looks like the following:
Order:
{
"country": "US", // or "CA" for Canada
"items": [
{"product": "mouse", "quantity": 20},
{"product": "laptop", "quantity": 5}
]
}
Note: In your solution you can pass in an in-memory object that has the same shape as the JSON.
You don’t need to worry about parsing JSON for this problem.
The US and CA orders have the same shape, they just represent different countries.
Shipping Cost Matrix
Each country and product has a corresponding shipping cost matrix.
The cost is stored in the smallest currency unit (e.g., cents).
ShippingCost:
{
"US": [
{"product": "mouse", "cost": 550},
{"product": "laptop", "cost": 1000}
],
"CA": [
{"product": "mouse", "cost": 750},
{"product": "laptop", "cost": 1100}
]
}
Task 1
Write a function called calculate_shipping_cost that takes in an order and a shipping cost matrix, and returns the total shipping cost.
Example
calculate_shipping_cost(order_us, shipping_cost)
calculate_shipping_cost(order_ca, shipping_cost)
Quantity-Based Discounts (Tiered Pricing)
For some items, shipping the first few units is more expensive than shipping additional units.
You need to update the shipping matrix to reflect quantity-based discounts.
The order remains the same, but the shipping cost matrix is now updated like the following:
Updated Shipping Cost Matrix (Tiered Discounts)
US
{
"US": [
{
"product": "mouse",
"costs": [
{"minQuantity": 0, "maxQuantity": null, "cost": 550}
]
},
{
"product": "laptop",
"costs": [
{"minQuantity": 0, "maxQuantity": 2, "cost": 1000},
{"minQuantity": 3, "maxQuantity": null, "cost": 900}
]
}
]
}
CA
{
"CA": [
{
"product": "mouse",
"costs": [
{"minQuantity": 0, "maxQuantity": null, "cost": 750}
]
},
{
"product": "laptop",
"costs": [
{"minQuantity": 0, "maxQuantity": 2, "cost": 1100},
{"minQuantity": 3, "maxQuantity": null, "cost": 1000}
]
}
]
}
Task 2
Update the function calculate_shipping_cost to now calculate shipping based on the tiered discount rules.
Example Output
calculate_shipping_cost(order_us, shipping_cost) # → 15700
calculate_shipping_cost(order_ca, shipping_cost) # → 20200
题目考点与难点
- 数据结构建模能力
要把 JSON-like 对象转成可操作的结构(dict/list)。 - 算法逻辑设计
需要根据数量匹配到对应区间。 - 复杂度控制
计算量应保持在 O(n),即按订单项遍历一遍即可。 - 可扩展性
如果未来新增更多国家或产品类型,函数仍能正确计算。
🔍 面试官常见追问
- 如果输入的国家不存在该产品,应返回什么?
- 如何扩展到全球运费矩阵?
- 是否能处理 10,000+ 产品的大订单?
- 你的算法在最坏情况下的时间和空间复杂度是多少?
✅ 总结
这是一道非常典型的 Stripe 系统设计风格算法题 ——
题干贴近真实业务逻辑(跨国运费、分层折扣),但核心仍是 数据结构 + 逻辑匹配 + 边界处理 。
在面试中,候选人应重点展示 清晰的逻辑表达、良好的命名与代码可读性。
🚀 延伸推荐
我们的 Stripe 模拟面试辅导 提供完整题目讲解、思维路径拆解,以及 mock 场景训练,帮助你在正式面试中快速进入状态、精准作答。