Design a Shopping Cart Withstacked Coupons & Restock Alerts
In a 45-minute LLD interview, this problem evaluates extensible pricing pipelines and event-driven stock alerts. Scope the solution to: cart line item accounting in integer paise (int64_t), dynamically stackable promotion rules chained via the Decorator pattern (CartPriceRule), pluggable shipping calculations via the Strategy pattern (ShippingStrategy), and out-of-stock alert dispatch to subscribed shoppers via the Observer pattern (RestockObserver). Real payment gateways and warehouse robotics can be left as high-level architectural follow-ups.
Problem statement & clarifying requirements
Design an e-commerce shopping cart with stackable coupon rules and inventory restock alerts. The system must allow customers to chain arbitrary discount promotions (such as percentage off, flat cart minimums, and category-capped coupons) using the Decorator Pattern, select shipping methods via the Strategy Pattern, and notify interested shoppers when out-of-stock items are replenished using the Observer Pattern.
Discounts are modeled as Decorator layers (CartPriceRule), wrapping a base cart total and computing discounts sequentially in the order applied.
Three distinct decorators: PercentageCouponDecorator (proportional deduction), FlatThresholdCouponDecorator (fixed rupee reduction once cart subtotal exceeds a floor), and CategoryCapCouponDecorator (percentage discount on a specific product category with a hard rupee cap).
Customers subscribe to out-of-stock SKUs. When the inventory service receives units for a SKU with zero prior stock, all registered observers receive an alert and the subscription list is cleared.
All prices, discounts, and thresholds are expressed in integer paise (int64_t) to avoid floating-point rounding issues.
First, sketch the design yourself
Spend 5 minutes listing the classes, who owns whom, and which interface hides the part that changes.
- 1.
Decorator Pattern (
c1) for dynamic promotion stacking: Hardcoding multiple discounts intoShoppingCartcreates rigid permutations. The Decorator pattern lets marketing teams stack coupons in arbitrary orders (e.g. category discount first, then storewide percentage, then flat promo) without altering cart models. - 2.
Observer Pattern (
a3) for loose inventory coupling:InventoryServiceshouldn't depend directly on customer messaging protocols (email, SMS, push). SubscribingRestockObserverimplementations allows adding new notification channels seamlessly. - 3.
Preserving invariants during discount chaining: Ensure each decorator clamps the computed cart total at
0so stacked discounts never produce negative balances.
How to think through this problem (5-step walkthrough)
In a 45-minute LLD interview, this problem evaluates extensible pricing pipelines and event-driven stock alerts. Scope the solution to: cart line item accounting in integer paise (int64_t), dynamically stackable promotion rules chained via the Decorator pattern (CartPriceRule), pluggable shipping calculations via the Strategy pattern (ShippingStrategy), and out-of-stock alert dispatch to subscribed shoppers via the Observer pattern (RestockObserver). Real payment gateways and warehouse robotics can be left as high-level architectural follow-ups.
Not every noun in the prompt deserves its own class. Separate dumb data structs from stateful managers, and turn trivial nouns into fields or enums.
CartPriceRuleBase component interface declaring pure virtual calculate(const ShoppingCart&): int64_t in integer paise, implemented by both base prices and coupon decorators.
BaseCartPriceLeaf component calculating the raw subtotal by summing line items (unitPricePaise * quantity) without any promotional adjustments.
PriceRuleDecoratorAbstract Decorator maintaining ownership of a std::unique_ptr<CartPriceRule> inner_ and delegating base calculations before applying specific deductions.
RestockObserverObserver interface declaring onRestocked(sku, availableQty) implemented by customer notification channels (Email, SMS, Push).
InventoryServiceSubject managing SKU inventory counts and notifying subscribed observers when an out-of-stock item receives fresh units.
ShippingStrategyStrategy interface for calculating shipping fees (StandardShipping with free tier vs ExpressShipping) based on cart total and shipping address.
DiscountedPrice / CouponCodeTrap noun β DiscountedPrice is not an entity; it is the scalar integer return value of calculate(). Similarly, a coupon code string or discount percentage is constructor configuration data passed into a concrete decorator, not a stateful domain class.
A naive approach places discount calculations directly inside ShoppingCart with cascading booleans: if (hasPercentOff) ... if (hasPromoCode) ... if (hasCategoryCoupon) .... This creates an exponential explosion of coupon ordering permutations, makes unit testing individual discounts impossible without mock carts, and violates the Open-Closed Principle whenever marketing dreams up a new promotion type.
Hardcoded discount methods in ShoppingCart prevent customers from chaining promo codes in arbitrary sequence (e.g. category coupon first, then percentage discount, then flat coupon).
Hardcoding email or SMS sending calls directly in InventoryService::addStock() tightly couples inventory management to notification providers.
Hardcoded shipping logic in the checkout flow prevents offering promotional free shipping, tiered rates, or courier-specific pricing.
- β
Non-negative pricing floor: Every
CartPriceRuledecorator must clamp its computed price at zero (std::max<int64_t>(0, discounted)), ensuring stacked promotions never generate negative payable totals. - β
Restock transition trigger: In
InventoryService, restock notifications are dispatched if and only if prior inventory was zero and new inventory is strictly greater than zero (prevQty == 0 && newQty > 0), avoiding spam on subsequent partial deliveries. - β
Integer currency invariant: All product unit prices, discounts, category caps, and shipping fees are computed in integer paise (
int64_t), preventing binary floating-point rounding discrepancies.
Entities & design patterns used
Unlock Full UML Diagram & C++23 Solution
The complete UML diagram, production-ready C++23 code, follow-up extensions, and design pitfall analysis are part of Brute2Best Pro. All 7 foundation chapters are 100% free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.