Skip to main content

Pizza Toppings Cost Analysis - Solution & Explanation

MediumPremiumFree on FleetCodeDatabase5 min readAsked at: Amazon
Practice this problem

Problem Statement

Table: Toppings

+--------------+---------+ 
| Column Name  | Type    | 
+--------------+---------+ 
| topping_name | varchar | 
| cost         | decimal |
+--------------+---------+
topping_name is the primary key for this table.
Each row of this table contains topping name and the cost of the topping. 

Write a solution to calculate the total cost of all possible 3-topping pizza combinations from a given list of toppings. The total cost of toppings must be rounded to 2 decimal places.

Note:

  • Do not include the pizzas where a topping is repeated. For example, ‘Pepperoni, Pepperoni, Onion Pizza’.
  • Toppings must be listed in alphabetical order. For example, 'Chicken, Onions, Sausage'. 'Onion, Sausage, Chicken' is not acceptable.

Return the result table ordered by total cost in descending order and combination of toppings in ascending order.

The result format is in the following example.

 

Example 1:

Input: 
Toppings table:
+--------------+------+
| topping_name | cost |
+--------------+------+
| Pepperoni    | 0.50 |
| Sausage      | 0.70 |
| Chicken      | 0.55 |
| Extra Cheese | 0.40 |
+--------------+------+
Output: 
+--------------------------------+------------+
| pizza                          | total_cost | 
+--------------------------------+------------+
| Chicken,Pepperoni,Sausage      | 1.75       |  
| Chicken,Extra Cheese,Sausage   | 1.65       |
| Extra Cheese,Pepperoni,Sausage | 1.60       |
| Chicken,Extra Cheese,Pepperoni | 1.45       | 
+--------------------------------+------------+
Explanation: 
There are only four different combinations possible with the three topings:
- Chicken, Pepperoni, Sausage: Total cost is $1.75 (Chicken $0.55, Pepperoni $0.50, Sausage $0.70).
- Chicken, Extra Cheese, Sausage: Total cost is $1.65 (Chicken $0.55, Extra Cheese $0.40, Sausage $0.70).
- Extra Cheese, Pepperoni, Sausage: Total cost is $1.60 (Extra Cheese $0.40, Pepperoni $0.50, Sausage $0.70).
- Chicken, Extra Cheese, Pepperoni: Total cost is $1.45 (Chicken $0.55, Extra Cheese $0.40, Pepperoni $0.50).
Output table is ordered by the total cost in descending order.

Approach Overview

Problem Overview: You are given a table of pizza toppings with their costs. The task is to generate valid topping combinations and compute the total price for each pizza configuration while avoiding duplicate permutations of the same toppings.

Approach 1: Conditional Self Join (Baseline SQL Strategy) (Time: O(n^3), Space: O(1))

The straightforward SQL strategy is joining the Toppings table with itself multiple times to generate combinations. Each join represents one topping in the pizza. To avoid duplicate permutations such as (pepperoni, cheese, olives) and (cheese, pepperoni, olives), apply ordering constraints like t1.id < t2.id < t3.id. This conditional join ensures each set of toppings appears exactly once. After generating the combination, compute the total cost using t1.cost + t2.cost + t3.cost and return the result sorted by total price and topping names.

This technique works because relational joins can enumerate combinations efficiently without explicit iteration logic. However, the query grows more complex as the number of toppings per pizza increases. The database engine effectively performs a combinational join, which conceptually behaves like O(n^3) for three toppings.

Approach 2: Window Function + Conditional Join (Optimized SQL Pattern) (Time: O(n^3), Space: O(n))

A cleaner approach assigns a deterministic order to toppings using a window function such as ROW_NUMBER(). The query first ranks toppings with ROW_NUMBER() OVER(ORDER BY topping_name). These row numbers act as stable indices. The table is then joined to itself with conditions like a.rn < b.rn AND b.rn < c.rn to construct unique triples.

The key insight is that window functions provide a predictable ordering independent of primary keys. This simplifies combination logic and prevents duplicates without complicated string comparisons. The join then aggregates the cost across the three selected toppings and returns the formatted pizza description along with the total cost.

This pattern appears frequently in advanced SQL and database interview problems where combinations must be generated while enforcing uniqueness. Window functions make the logic explicit and easier to maintain. Many engineers prefer this version because the ranking step separates ordering from the join logic.

Recommended for interviews: Interviewers usually expect the conditional self‑join idea first since it demonstrates understanding of SQL joins and combination constraints. The window function version shows stronger SQL fluency and familiarity with analytical features from window functions. Both approaches produce the same result, but the ranked join pattern tends to be clearer and more scalable in real systems.

Solution

First, we use a window function to sort the table by the topping_name field and add a rk field to each row, representing the ranking of the current row.

Then we use conditional join to join the table T three times, named as t1, t2, t3 respectively. The join conditions are t1.rk < t2.rk and t2.rk < t3.rk. After that, we calculate the total price of the three toppings, sort by total price in descending order, and then sort by topping name in ascending order.

Code

MySQL

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Conditional Self JoinO(n^3)O(1)Simple SQL queries where topping combinations are generated directly using ordered join conditions
Window Function + Conditional JoinO(n^3)O(n)Preferred when deterministic ordering is needed or when primary keys are unreliable for combination logic

Video Solution

McKinsey & Company | Leetcode Premium | 3050 | Pizza Toppings Cost Analysis • DEwithDhairy • 1,307 views views

Watch 1 more video solutions →

Frequently Asked Questions

Is Pizza Toppings Cost Analysis easy or hard?
Pizza Toppings Cost Analysis is generally classified as a Medium difficulty SQL problem. The challenge comes from generating unique combinations without duplicates and formatting the results correctly. Familiarity with self joins and window functions makes the solution straightforward.
Pizza Toppings Cost Analysis Python/Java solution
This problem is designed as a SQL database challenge rather than a typical algorithm implementation in Python or Java. The solution is written as a SQL query using joins and window functions. Platforms that support MySQL typically solve it using ROW_NUMBER() and conditional joins.
How to solve Pizza Toppings Cost Analysis in O(n)?
An O(n) solution is not feasible because the problem requires generating combinations of multiple toppings. Any method that enumerates triples of toppings requires examining combinations, which leads to O(n^3) complexity. SQL solutions focus on writing efficient joins rather than reducing the theoretical complexity.
What is the best approach for Pizza Toppings Cost Analysis?
The most practical solution uses a window function to assign row numbers and then performs conditional self joins to generate unique topping combinations. This prevents duplicate permutations and keeps the SQL logic clean. The approach works well in MySQL using ROW_NUMBER() with join conditions such as a.rn < b.rn < c.rn.
Is Pizza Toppings Cost Analysis asked at Google/Amazon/Meta?
SQL combination and aggregation problems like Pizza Toppings Cost Analysis appear frequently in database interviews at companies such as Amazon, Google, and Meta. The exact question may vary, but generating unique combinations with joins and window functions is a common interview pattern.
What data structure is used in Pizza Toppings Cost Analysis?
The problem relies on relational tables and SQL joins rather than traditional in‑memory data structures. Internally, the database engine may use hash joins, sort operations, or temporary tables to process the query. Window functions help assign ordering indexes used to build valid combinations.
What is the time complexity of Pizza Toppings Cost Analysis?
The logical complexity is O(n^3) because the query generates combinations of three toppings from the toppings table. Each join layer multiplies the number of candidate rows. In practice, database optimizers can reduce some overhead, but the combination count still grows cubically with the number of toppings.

Ready to solve this problem?

Practice Pizza Toppings Cost Analysis with our built-in code editor and test cases.

Practice on FleetCode