Dynamic Pivoting of a Table — LeetCode 2252 Python Solution

HardLeetCode PremiumDatabase
Problem
#2252
Reading time
4 min

Table schema

SQL
Table: Products +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | store | varchar | | price | int | +-------------+---------+ (product_id, store) is the primary key (combination of columns with unique values) for this table. Each row of this table indicates the price of product_id in store.

Example

SQL
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store       | varchar |
| price       | int     |
+-------------+---------+
(product_id, store) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the price of product_id in store.
There will be at most 30 different stores in the table.
price is the price of the product at this store.

Python solution

Python
import duckdb
import pandas as pd

def solution(products: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Products", products)
    return con.execute("""CREATE PROCEDURE PivotProducts()
BEGIN
	SET group_concat_max_len = 5000;
    SELECT GROUP_CONCAT(DISTINCT 'MAX(CASE WHEN store = \'',
               store,
               '\' THEN price ELSE NULL END) AS ',
               store
               ORDER BY store) INTO @sql
    FROM Products;
    SET @sql =  CONCAT('SELECT product_id, ',
                    @sql,
                    ' FROM Products GROUP BY product_id');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2252. Dynamic Pivoting of a Table?
LeetCode 2252. Dynamic Pivoting of a Table is rated Hard on LeetCode.
What topics does LeetCode 2252. Dynamic Pivoting of a Table cover?
LeetCode 2252. Dynamic Pivoting of a Table is tagged Database on LeetCode.
Is LeetCode 2252. Dynamic Pivoting of a Table a premium problem?
Yes. LeetCode 2252. Dynamic Pivoting of a Table is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview