Talentd
FleetCode
Make and follow sheets.Sign in

Rearrange Products Table solution and explanation

EasyDatabase6 min read85.4% acceptanceUpdated 9 Apr 2026
LeetCode 1795 Interview SQL Question with Detailed Explanation | Practice SQLEveryday Data Science · 12:05 · 8K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode 1795 Interview SQL Question with Detailed Explanation | Practice SQLEveryday Data Science · 12:05 · 8K views
  2. SQL Skills That Sell: Prep for High-Paying Job Interviews! - Data Science | Leetcode 1795Everyday Data Science · 4:59 · 1K views
  3. LeetCode 1795 | Rearrange Products Table | Union all | SQLSleepy Cracker · 3:30 · 648 views
  4. 1795. Rearrange Products Table | LeetCode | SQL | Solution | Interview ProblemData Alchemist · 6:51 · 559 views
  5. Solving LeetCode problem 1795 in APL (Rearrange Products Table)Rodrigo's APL Corner · 10:37 · 383 views
  6. Rearrange Products Table (Leetcode 1795) in TeluguCoding Interview Preparation · 6:20 · 260 views
  7. Rearrange Products Table #leetcode #mssqlserver #easyWinEi · 4:09 · 129 views
  8. 【Leetcode Pandas 10/30】1795. Rearrange Products Table (~Easy) df.melt for converting wide into long~思臉AI · 3:19 · 127 views
  9. 30 Days of Pandas Day 15 | Rearrange Products Table | LeetCode 1795DevTechMinds · 7:45 · 119 views
  10. LeetCode SQL Study Plan || Rearrange Products Table || Unpivot in SQLBHAVESH HARIRAMANI · 5:27 · 78 views

The problem

Table: Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store1      | int     |
| store2      | int     |
| store3      | int     |
+-------------+---------+
product_id is the primary key (column with unique values) for this table.
Each row in this table indicates the product's price in 3 different stores: store1, store2, and store3.
If the product is not available in a store, the price will be null in that store's column.

Write a solution to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table.

Return the result table in any order.

The result format is in the following example.

Example 1:

Input: 
Products table:
+------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+------------+--------+--------+--------+
| 0          | 95     | 100    | 105    |
| 1          | 70     | null   | 80     |
+------------+--------+--------+--------+
Output: 
+------------+--------+-------+
| product_id | store  | price |
+------------+--------+-------+
| 0          | store1 | 95    |
| 0          | store2 | 100   |
| 0          | store3 | 105   |
| 1          | store1 | 70    |
| 1          | store3 | 80    |
+------------+--------+-------+
Explanation: 
Product 0 is available in all three stores with prices 95, 100, and 105 respectively.
Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.

Approach overview

Problem Overview: You are given a Products table where each row contains a product_id and multiple store columns (store1, store2, store3). The task is to transform this wide table into a normalized row format: each non-null store price becomes a separate row with columns product_id, store, and price. This is essentially an unpivot operation commonly seen in database transformations.

Approach 1: Iterative Row and Column Traversal (O(n*k) time, O(1) extra space)

Treat the table like a small matrix: iterate through each product row, then check each store column individually. For every store field (store1, store2, store3), verify whether the value is non-null. When a price exists, emit a new row containing the product_id, the store name, and the price. The key insight is that the number of store columns is fixed and small, so a simple nested traversal works efficiently. This approach maps naturally to languages like Python or C# where you loop through rows and manually construct the output records. Time complexity is O(n*k), where n is the number of products and k is the number of store columns. Extra space is O(1) beyond the output since you only track the current row and column being processed. The pattern resembles iterating over a matrix with conditional filtering.

Approach 2: SQL-like Transformation with Language Features (O(n*k) time, O(k) space)

This approach models the solution after SQL UNPIVOT behavior using built-in language features. Create a small structure (array, map, or list) that pairs store names with their corresponding column values for each row. For example, convert a row into something like [("store1", value1), ("store2", value2), ("store3", value3)]. Iterate through this structure and append an output record whenever the value is not null. Languages like JavaScript or C make this clean by storing the store names in an array and iterating through them dynamically. The main insight is separating column metadata (store names) from row data, which simplifies the transformation logic. Time complexity remains O(n*k) since every product checks every store column. Space complexity is O(k) for the temporary store mapping used during each iteration. This style mirrors transformations commonly used in array-driven data reshaping pipelines.

Recommended for interviews: The iterative row and column traversal approach is typically expected. It clearly shows you understand how to normalize wide data structures by scanning each column and filtering null values. Demonstrating the SQL-style transformation afterward shows deeper familiarity with data reshaping patterns and how unpivot operations are implemented outside SQL engines.

Approach 1: Approach 1: Iterative Row and Column Traversal

This approach involves iterating over each row of the original table and for each product, iterating over the store columns. For each store, if the price is not null, a new entry with the product_id, store name, and price is added to the result.

def rearrange_products(products):
    result = []
    stores = ['store1', 'store2', 'store3']
    for product in products:
        product_id = product['product_id']
        for store in stores:
            if product[store] is not None:
                result.append({'product_id': product_id, 'store': store, 'price': product[store]})
    return result

# Example usage
products = [{'product_id': 0, 'store1': 95, 'store2': 100, 'store3': 105}, {'product_id': 1, 'store1': 70, 'store2': None, 'store3': 80}]
print(rearrange_products(products))
using System;
using System.Collections.Generic;

class Program {
    public static List<Dictionary<string, object>> RearrangeProducts(List<Dictionary<string, object>> products) {
        var result = new List<Dictionary<string, object>>();
        var stores = new List<string> { "store1", "store2", "store3" };
        foreach (var product in products) {
            foreach (var store in stores) {
                if (product[store] != null) {
                    result.Add(new Dictionary<string, object> {
                        { "product_id", product["product_id"] },
                        { "store", store },
                        { "price", product[store] }
                    });
                }
            }
        }
        return result;
    }

    static void Main() {
        var products = new List<Dictionary<string, object>> {
            new Dictionary<string, object> { { "product_id", 0 }, { "store1", 95 }, { "store2", 100 }, { "store3", 105 } },
            new Dictionary<string, object> { { "product_id", 1 }, { "store1", 70 }, { "store2", null }, { "store3", 80 } }
        };
        var result = RearrangeProducts(products);
        foreach (var row in result) {
            Console.WriteLine($"{{product_id: {row["product_id"]}, store: {row["store"]}, price: {row["price"]}}}");
        }
    }
}

This solution defines a function rearrange_products that takes a list of dictionaries as input, representing rows from the Products table. It iterates through each product and nested within that loop, iterates over the stores to check if the price is available. If so, the function appends a dictionary with the product_id, store, and price to the result list.

Complexity

Time Complexity: O(n * m), where n is the number of products and m is the number of stores. Space Complexity: O(n * m), as we store results for each product-store where a price exists.

Try this approach in the editor

Approach 2: Approach 2: SQL-like Transformation with Language Features

Using language constructs similar to SQL's UNPIVOT operation, we will extract non-null values for each store and create a new list with structure (product_id, store, price).

function rearrangeProducts(products) {
    let result = [];
    products.forEach(product => {
        const productId = product['product_id'];
        ['store1', 'store2', 'store3'].forEach(store => {
            if (product[store] !== null) {
                result.push({product_id: productId, store: store, price: product[store]});
            }
        });
    });
    return result;
}

// Example usage
const products = [
    { product_id: 0, store1: 95, store2: 100, store3: 105 },
    { product_id: 1, store1: 70, store2: null, store3: 80 }
];
console.log(rearrangeProducts(products));
#include <stdio.h>
#include <stdlib.h>

void rearrangeProducts(int products[][4], int num_products) {
    for (int i = 0; i < num_products; i++) {
        int productId = products[i][0];
        for (int store = 1; store <= 3; store++) {
            if (products[i][store] != -1) { // Assuming -1 as a placeholder for NULL
                printf("Product ID: %d, Store: store%d, Price: %d\n", productId, store, products[i][store]);
            }
        }
    }
}

int main() {
    int products[2][4] = {
        {0, 95, 100, 105},
        {1, 70, -1, 80}
    };
    rearrangeProducts(products, 2);
    return 0;
}

This JavaScript solution leverages functions like forEach to iterate over products and stores, adding new objects to result when a store has a non-null price.

Complexity

Time Complexity: O(n * m), Space Complexity: O(n * m).

Try this approach in the editor

Approach 3: Union

We can select the products and prices for each store, and then use the UNION operator to combine the results.

# Write your MySQL query statement below
SELECT product_id, 'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL
UNION
SELECT product_id, 'store2' AS store, store2 AS price FROM Products WHERE store2 IS NOT NULL
UNION
SELECT product_id, 'store3' AS store, store3 AS price FROM Products WHERE store3 IS NOT NULL;
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Iterative Row and Column Traversal

Time Complexity: O(n * m), where n is the number of products and m is the number of stores. Space Complexity: O(n * m), as we store results for each product-store where a price exists.

Approach 2: SQL-like Transformation with Language Features

Time Complexity: O(n * m), Space Complexity: O(n * m).

Union–

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterative Row and Column TraversalO(n*k)O(1)Best when the number of store columns is small and fixed; simple and interview-friendly.
SQL-like Transformation with Language FeaturesO(n*k)O(k)Useful when implementing generic column-to-row transformations or mimicking SQL UNPIVOT behavior.

Frequently asked questions

Is Rearrange Products Table easy or hard?

Rearrange Products Table is categorized as an Easy problem with an acceptance rate above 85%. The logic is straightforward once you recognize that the task is an unpivot transformation that converts column-based store prices into individual rows.

Rearrange Products Table Python/Java solution

In Python or Java-style solutions, iterate through each row and manually check store1, store2, and store3. For each non-null value, append a record with product_id, store name, and price. This direct traversal approach keeps the implementation simple and runs in O(n*k) time.

How to solve Rearrange Products Table in O(n)?

Treat the number of store columns as a constant. Iterate through every product row once and check each store column directly. Because there are only three store columns, the complexity becomes O(n*3), which simplifies to O(n) in practice.

What is the best approach for Rearrange Products Table?

The most practical approach is iterative row and column traversal. Iterate through each product row and check each store column (store1, store2, store3). Whenever the value is not null, output a row containing product_id, store name, and price. This runs in O(n*k) time where n is the number of rows and k is the number of store columns.

Is Rearrange Products Table asked at Google/Amazon/Meta?

Problems involving table normalization and unpivot operations appear frequently in database interviews at companies like Amazon and Meta. They test your understanding of relational data transformations, especially converting wide tables into row-based formats.

What data structure is used in Rearrange Products Table?

The solution primarily works with tabular data structures similar to arrays of records. During processing, many implementations temporarily store store-name/value pairs in arrays or small maps to simulate a SQL UNPIVOT transformation.

What is the time complexity of Rearrange Products Table?

The time complexity is O(n*k). Each of the n product rows must check k store columns to determine whether a price exists. Since k is small and fixed in the problem, the solution effectively scales linearly with the number of rows.

Comments

Now write it yourselfClose this page and solve Rearrange Products Table in the editor, without looking.
Practise Rearrange Products Table