Skip to main content

Calculate Product Final Price - Solution & Explanation

MediumPremiumFree on FleetCodeDatabase5 min read
Practice this problem

Problem Statement

Table: Products

+------------+---------+ 
| Column Name| Type    | 
+------------+---------+ 
| product_id | int     | 
| category   | varchar |
| price      | decimal |
+------------+---------+
product_id is the unique key for this table.
Each row includes the product's ID, its category, and its price.

Table: Discounts

+------------+---------+ 
| Column Name| Type    | 
+------------+---------+ 
| category   | varchar |
| discount   | int     |
+------------+---------+
category is the primary key for this table.
Each row contains a product category and the percentage discount applied to that category (values range from 0 to 100).

Write a solution to find the final price of each product after applying the category discount. If a product's category has no associated discount, its price remains unchanged.

Return the result table ordered by product_id in ascending order.

The result format is in the following example.

 

Example:

Input:

Products table:

+------------+-------------+-------+
| product_id | category    | price |
+------------+-------------+-------+
| 1          | Electronics | 1000  |
| 2          | Clothing    | 50    |
| 3          | Electronics | 1200  | 
| 4          | Home        | 500   |
+------------+-------------+-------+
  

Discounts table:

+------------+----------+
| category   | discount |
+------------+----------+
| Electronics| 10       |
| Clothing   | 20       |
+------------+----------+
  

Output:

+------------+------------+-------------+
| product_id | final_price| category    |
+------------+------------+-------------+
| 1          | 900        | Electronics |
| 2          | 40         | Clothing    |
| 3          | 1080       | Electronics |
| 4          | 500        | Home        |
+------------+------------+-------------+
  

Explanation:

  • For product 1, it belongs to the Electronics category which has a 10% discount, so the final price is 1000 - (10% of 1000) = 900.
  • For product 2, it belongs to the Clothing category which has a 20% discount, so the final price is 50 - (20% of 50) = 40.
  • For product 3, it belongs to the Electronics category and receives a 10% discount, so the final price is 1200 - (10% of 1200) = 1080.
  • For product 4, no discount is available for the Home category, so the final price remains 500.
Result table is ordered by product_id in ascending order.

Approach Overview

Problem Overview: You are given product data along with a table containing discount information. The task is to compute the final price of each product after applying the available discount. If a product has no matching discount entry, its original price should remain unchanged.

Approach 1: Correlated Subquery Lookup (O(n*m) time, O(1) space)

A straightforward approach is to iterate through every product and look up its discount using a correlated subquery. For each row in the Products table, a subquery searches the discount table to retrieve the discount percentage and computes price * (1 - discount / 100). While simple, this approach forces the database engine to run a lookup for every product row. With large datasets, repeated scans of the discount table significantly increase query cost. This method mainly demonstrates the logic but is rarely the preferred production solution.

Approach 2: LEFT JOIN (O(n + m) time, O(1) extra space)

The efficient solution joins the Products table with the discount table using a LEFT JOIN. The join matches rows based on the product identifier (or category, depending on schema). A left join guarantees that every product appears in the result set, even if no discount record exists. After joining, compute the final price using an expression like price * (1 - IFNULL(discount, 0) / 100). The database performs the join once instead of running repeated lookups, making the query scale much better.

This approach works well because relational databases are optimized for join operations. Indexes on the join keys allow the engine to match rows efficiently. In frameworks like Pandas, the same idea applies using merge(..., how='left'), which preserves all product rows and fills missing discount values with nulls that can be replaced with zero.

Understanding join behavior is critical for many database interview questions. The pattern of combining datasets with SQL queries and handling missing matches using LEFT JOIN appears frequently in analytics pipelines and reporting tasks. You also gain practice working with relational operations like those covered under joins.

Recommended for interviews: Interviewers expect the LEFT JOIN approach. It demonstrates that you understand relational joins and how to preserve unmatched rows while applying calculations. Mentioning the naive correlated lookup first shows baseline understanding, but the optimized join solution signals strong SQL fundamentals.

Solution

We can perform a left join between the Products table and the Discounts table on the category column, then calculate the final price. If a product's category does not have an associated discount, its price remains unchanged.

Code

MySQL

Pandas

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Correlated Subquery LookupO(n * m)O(1)Small datasets or when demonstrating baseline SQL logic without joins
LEFT JOINO(n + m)O(1)Preferred solution for combining product and discount tables efficiently

Video Solution

Leetcode MEDIUM 3293 - Calculate Product Final Price - Using IFNULL in SQL | Everyday Data ScienceEveryday Data Science486 views views

Frequently Asked Questions

Is Calculate Product Final Price easy or hard?
The problem is typically considered medium difficulty because it requires understanding how joins work and how to handle missing matches correctly. The SQL itself is short, but recognizing when to use a LEFT JOIN instead of a subquery is the key concept.
Calculate Product Final Price Python/Java solution
In SQL environments like MySQL, the solution uses a LEFT JOIN and a price calculation expression. In Python with Pandas, the equivalent approach uses DataFrame.merge(..., how='left') followed by a vectorized calculation of the final price column. Java database solutions typically execute the same SQL join query through JDBC.
How to solve Calculate Product Final Price in O(n)?
Use a LEFT JOIN to combine the product table with the discount table based on the matching key. After the join, compute the final price using an arithmetic expression that substitutes missing discounts with zero using IFNULL or COALESCE. This avoids repeated lookups and processes the dataset in a single join pass.
What is the best approach for Calculate Product Final Price?
The most efficient solution uses a LEFT JOIN between the products table and the discounts table. This guarantees that every product remains in the result set even when no discount exists. The final price is calculated with an expression such as price * (1 - IFNULL(discount,0)/100). This approach runs in roughly O(n + m) time depending on indexing.
Is Calculate Product Final Price asked at Google/Amazon/Meta?
SQL join and price‑calculation problems appear frequently in interviews at companies like Amazon, Google, and data‑focused roles across tech companies. While the exact problem may vary, the core concept—joining tables and applying conditional calculations—is a common database interview pattern.
What data structure is used in Calculate Product Final Price?
The problem relies on relational database tables and SQL join operations rather than traditional in‑memory data structures. The key concept is the LEFT JOIN, which merges rows from two tables while preserving all rows from the left table.
What is the time complexity of Calculate Product Final Price?
The optimized SQL solution using a LEFT JOIN runs in O(n + m) time where n is the number of products and m is the number of discount rows. Database engines typically use indexed joins to match rows efficiently. The space complexity is O(1) because the computation happens during query execution without additional data structures.

Ready to solve this problem?

Practice Calculate Product Final Price with our built-in code editor and test cases.

Practice on FleetCode