2Brute2Best
πŸ”₯0
P14

Design a Shopping Cart Withstacked Coupons & Restock Alerts

Medium Pro OnlyObserverDecoratorStrategy
⚑ 30-Second Interview Cheat SheetP14 · 45-Min Design Plan
3 Patterns Combined
1. Scope Boundaries

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.

2. Core Noun Entities
CartPriceRuleinterface
BaseCartPricestateful-class
PriceRuleDecoratorinterface
RestockObserverinterface
3. Hotspot β†’ Pattern
Dynamic stacking and sequencing of discount promotions β†’ Decorator Pattern (CartPriceRule wrapping BaseCartPrice)
Back-in-stock customer notifications β†’ Observer Pattern (RestockObserver with InventoryService as Subject)
Shipping fee calculation policies β†’ Strategy Pattern (ShippingStrategy)
01

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.

Questions you should ask the interviewer first
β€œHow are stackable discount promotions composed?”

Discounts are modeled as Decorator layers (CartPriceRule), wrapping a base cart total and computing discounts sequentially in the order applied.

β€œWhat types of discount coupons must be supported?”

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).

β€œHow do restock alerts work when an item arrives back in stock?”

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.

β€œWhat currency unit is used across cart calculations?”

All prices, discounts, and thresholds are expressed in integer paise (int64_t) to avoid floating-point rounding issues.

02

First, sketch the design yourself

Spend 5 minutes listing the classes, who owns whom, and which interface hides the part that changes.

  1. 1.

    Decorator Pattern (c1) for dynamic promotion stacking: Hardcoding multiple discounts into ShoppingCart creates 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. 2.

    Observer Pattern (a3) for loose inventory coupling: InventoryService shouldn't depend directly on customer messaging protocols (email, SMS, push). Subscribing RestockObserver implementations allows adding new notification channels seamlessly.

  3. 3.

    Preserving invariants during discount chaining: Ensure each decorator clamps the computed cart total at 0 so stacked discounts never produce negative balances.

03

How to think through this problem (5-step walkthrough)

Step 1 Β· Scope the 45-minute target & core boundary

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.

Step 2 Β· Extract candidate nouns (and reject false classes)

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.

CartPriceRule
Abstract Interface

Base component interface declaring pure virtual calculate(const ShoppingCart&): int64_t in integer paise, implemented by both base prices and coupon decorators.

BaseCartPrice
Stateful Class / Manager

Leaf component calculating the raw subtotal by summing line items (unitPricePaise * quantity) without any promotional adjustments.

PriceRuleDecorator
Abstract Interface

Abstract Decorator maintaining ownership of a std::unique_ptr<CartPriceRule> inner_ and delegating base calculations before applying specific deductions.

RestockObserver
Abstract Interface

Observer interface declaring onRestocked(sku, availableQty) implemented by customer notification channels (Email, SMS, Push).

InventoryService
Stateful Class / Manager

Subject managing SKU inventory counts and notifying subscribed observers when an out-of-stock item receives fresh units.

ShippingStrategy
Abstract Interface

Strategy interface for calculating shipping fees (StandardShipping with free tier vs ExpressShipping) based on cart total and shipping address.

DiscountedPrice / CouponCode
Reject as Class β†’ Field / Method

Trap 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.

Step 3 Β· Draft the naive design & spot what breaks

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.

Step 4 Β· Map change hotspots to design patterns
Dynamic stacking and sequencing of discount promotions→ Decorator Pattern (CartPriceRule wrapping BaseCartPrice)

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).

Back-in-stock customer notifications→ Observer Pattern (RestockObserver with InventoryService as Subject)

Hardcoding email or SMS sending calls directly in InventoryService::addStock() tightly couples inventory management to notification providers.

Shipping fee calculation policies→ Strategy Pattern (ShippingStrategy)

Hardcoded shipping logic in the checkout flow prevents offering promotional free shipping, tiered rates, or courier-specific pricing.

Step 5 Β· Lock down C++23 ownership, invariants & concurrency
  • βœ“

    Non-negative pricing floor: Every CartPriceRule decorator 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.

04

Entities & design patterns used

Brute2Best Pro Content

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.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Systems Integration

Related C++ Systems & Algorithmic Foundations

Deep dive into underlying layers