Allocate Order Shipping Cost to Line Items Without Losing a Cent
Last updated: November 29, 2026
Quick Overview
Each shipment has one shipping cost in cents, but finance needs cost at the order line level. Given lines (order_id, line_id, weight_kg) and shipments (order_id, ship_cost_cents), use pandas to allocate each order's cost to its lines in proportion to weight, in whole cents, so that line amounts sum exactly to the order cost.
Amazon
November 29, 20260
0
0 solved
Each shipment has one shipping cost in cents, but finance needs cost at the order line level. Given lines (order_id, line_id, weight_kg) and shipments (order_id, ship_cost_cents), use pandas to allocate each order's cost to its lines in proportion to weight, in whole cents, so that line amounts sum exactly to the order cost.
Product-level profitability at Amazon depends on pushing shared costs like shipping down to the ASIN, and finance rejects any allocation that does not tie out to the invoice. Onsite data rounds use this to test vectorized groupby transforms and whether the candidate knows a rounding scheme, such as largest remainder, that preserves totals.
What the Interviewer Expects
- Compute proportional shares with groupby transform, not a Python loop over orders
- Recognize that independent rounding does not preserve totals
- Apply largest remainder: floor, then hand leftover cents to the largest fractional parts
- Break remainder ties deterministically
- Handle zero-weight orders and validate the one-to-many merge
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you allocate by a blend of weight and volume (dimensional weight)?
- What if some lines are returned and their allocated cost must be reversed?
- How would you write the largest remainder step in SQL?
- Why might finance prefer allocating by revenue instead of weight, and what does that change?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
lines(order_id, line_id, weight_kg);shipments(order_id, ship_cost_cents)with exactly one row per order (I validate many-to-one in the merge).- Allocation is proportional to weight. If every l...
Approach
- Merge cost onto lines.
- Share = line weight / order weight via
transform("sum"), or 1/n for zero-weight orders. - Exact allocation = cost x share. Rounding each value independently can be off ...