Problem · Hash Table

Shipping Cost Calculator Part 2 - Volume-Tiered Pricing

Learn this problem
MediumStripe logoStripeINTERNFULLTIMEPHONE SCREEN
See Stripe hiring insights

Problem statement

This continues the shipping cost calculator. Now each product's per-unit cost varies by quantity using tiered (volume-discount) pricing.

Inputs:

  • country: the destination country code.
  • items: a String[] of "product,quantity".
  • rules: a String[] of tier rules, each "country,product,minQuantity,maxQuantity,cost". A maxQuantity of * means the tier has no upper limit.

For each item, walk that product's tiers in ascending order. The range of a tier is half-open [minQuantity, maxQuantity), so the tier's capacity is maxQuantity - minQuantity (unbounded if maxQuantity is *). Assign as many remaining units as fit into each tier (the smaller of remaining units and the tier capacity), charge units * cost for those units, and continue until all units are priced. Sum across all items and return the total integer cost.

Function

calculateTieredShippingCost(country: String, items: String[], rules: String[]) → int

Examples

Example 1

country = "US"items = ["mouse,20", "laptop,5"]rules = ["US,mouse,0,*,550", "US,laptop,0,2,1000", "US,laptop,3,*,900", "CA,mouse,0,*,750", "CA,laptop,0,2,1100", "CA,laptop,3,*,1000"]return = 15700
US rates. mouse: 20 x 550 = 11000 (single unbounded tier). laptop (5 units): tier [0,2) holds 2 units at 1000 = 2000, tier [3,*) holds the remaining 3 units at 900 = 2700, laptop total 4700. Grand total 11000 + 4700 = 15700.

Example 2

country = "CA"items = ["mouse,20", "laptop,5"]rules = ["US,mouse,0,*,550", "US,laptop,0,2,1000", "US,laptop,3,*,900", "CA,mouse,0,*,750", "CA,laptop,0,2,1100", "CA,laptop,3,*,1000"]return = 20200
CA rates. mouse: 20 x 750 = 15000. laptop (5 units): tier [0,2) 2 units x 1100 = 2200, tier [3,*) 3 units x 1000 = 3000, laptop total 5200. Grand total 15000 + 5200 = 20200.

Constraints

  • rules entries are "country,product,minQuantity,maxQuantity,cost"; maxQuantity = * means unbounded.
  • Process a product's tiers from lowest to highest minQuantity.
  • The tier range is half-open [minQuantity, maxQuantity); capacity = maxQuantity - minQuantity.
  • Each tier prices min(remaining units, tier capacity) * cost.
  • Return the total cost across all items as an integer.

More Stripe problems

drafts saved locally
public int calculateTieredShippingCost(String country, String[] items, String[] rules) {
  // write your code here
}
country"US"
items["mouse,20", "laptop,5"]
rules["US,mouse,0,*,550", "US,laptop,0,2,1000", "US,laptop,3,*,900", "CA,mouse,0,*,750", "CA,laptop,0,2,1100", "CA,laptop,3,*,1000"]
expected15700
checking account