algorithm
e-commerce
discounts
pricing strategy
shopping cart optimization

e-commerce Algorithm for calculating discounts

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A discount engine is not just a formula that subtracts money from a cart total. In a real e-commerce system, the algorithm has to decide eligibility, priority, stackability, rounding, caps, and which rule wins when two promotions target the same items.

Start with Rule Semantics, Not Math

Before writing code, define what kinds of discounts exist. Common categories include:

  • percentage off an item or cart
  • fixed-amount discount
  • buy-one-get-one or bundle rules
  • threshold promotions such as "spend 100, save 10"
  • customer-segment or coupon-based rules

The real algorithm is the rule-evaluation order plus conflict handling, not only the arithmetic.

A practical engine usually evaluates promotions in a deterministic order so the same cart always gets the same answer.

Represent the Cart and Rules Explicitly

A small Python example shows a clean way to model a cart and apply simple promotions.

python
1from dataclasses import dataclass
2from typing import List
3
4@dataclass
5class LineItem:
6    sku: str
7    unit_price: float
8    quantity: int
9
10    @property
11    def subtotal(self) -> float:
12        return self.unit_price * self.quantity
13
14
15def cart_total(items: List[LineItem]) -> float:
16    return sum(item.subtotal for item in items)
17
18
19def apply_percentage_discount(total: float, percent: float) -> float:
20    return total * (1.0 - percent / 100.0)
21
22
23def apply_threshold_discount(total: float, threshold: float, amount_off: float) -> float:
24    return total - amount_off if total >= threshold else total
25
26
27items = [
28    LineItem("SKU-1", 40.0, 2),
29    LineItem("SKU-2", 30.0, 1),
30]
31
32total = cart_total(items)
33total = apply_threshold_discount(total, threshold=100.0, amount_off=10.0)
34total = apply_percentage_discount(total, percent=5.0)
35print(round(total, 2))

This example is simple, but it highlights an important truth: the outcome changes depending on the order in which rules are applied.

Order Matters

Suppose a cart qualifies for both:

  • '10 off when subtotal is at least 100'
  • '5% off the post-discount total'

Applying the fixed discount first gives a different result than applying the percentage first. That means the business needs a policy such as:

  • threshold promotions first, then cart percentage discounts
  • or highest priority first regardless of type
  • or best-price-for-customer if the platform allows promotion competition

The algorithm is incomplete until this ordering rule is explicit.

Item-Level Versus Cart-Level Discounts

Some discounts target only specific products, categories, or quantities. Others target the whole cart.

That distinction matters because cart-level discounts should not accidentally reduce excluded items such as gift cards or regulated products.

A disciplined engine usually works in layers:

  1. determine eligible line items
  2. apply line-item promotions
  3. recompute the discounted subtotal
  4. apply cart-level promotions
  5. apply shipping or payment-method incentives if relevant

That layering keeps the math auditable.

BOGO and Bundle Rules Need Matching Logic

Buy-one-get-one style promotions are really allocation problems. The engine has to decide which items are considered the paid ones and which become discounted.

For example, in a "buy two, get one free" rule, the common policy is to discount the cheapest eligible item in each qualifying group. That prevents over-discounting and gives a deterministic result.

Those rules are usually easier to implement after sorting eligible line items by price and quantity-expanding them when needed.

Guardrails the Engine Needs

A discount engine should also enforce:

  • stackability rules so incompatible promotions do not combine accidentally
  • maximum discount caps
  • coupon validity windows
  • customer eligibility checks
  • rounding rules that match payment and tax requirements

Without those rules, the algorithm may be mathematically correct but operationally wrong.

Common Pitfalls

Treating discount logic as one formula is the biggest mistake. In production, discounting is a rule system with conflicts and priorities.

Failing to define promotion order causes inconsistent totals across services and user interfaces.

Applying cart discounts to ineligible items also creates pricing bugs that are hard to reconcile later.

Finally, never rely on floating-point arithmetic casually in payment code. In real systems, use a decimal-safe money representation that matches your platform and currency rules.

Summary

  • an e-commerce discount algorithm is mainly a rule-evaluation and conflict-resolution problem
  • define promotion types, eligibility, and ordering before writing arithmetic code
  • separate item-level and cart-level discounts so eligibility stays clear
  • BOGO and bundle offers usually require explicit matching and allocation rules
  • use deterministic priorities, caps, and safe money handling so the same cart always produces the same result

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.