Skip to main content

Reshape Data: Melt - Solution & Explanation

Easy4 min readAsked at: Amazon, Bloomberg
Practice this problem

Problem Statement

DataFrame report
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| product     | object |
| quarter_1   | int    |
| quarter_2   | int    |
| quarter_3   | int    |
| quarter_4   | int    |
+-------------+--------+

Write a solution to reshape the data so that each row represents sales data for a product in a specific quarter.

The result format is in the following example.

 

Example 1:

Input:
+-------------+-----------+-----------+-----------+-----------+
| product     | quarter_1 | quarter_2 | quarter_3 | quarter_4 |
+-------------+-----------+-----------+-----------+-----------+
| Umbrella    | 417       | 224       | 379       | 611       |
| SleepingBag | 800       | 936       | 93        | 875       |
+-------------+-----------+-----------+-----------+-----------+
Output:
+-------------+-----------+-------+
| product     | quarter   | sales |
+-------------+-----------+-------+
| Umbrella    | quarter_1 | 417   |
| SleepingBag | quarter_1 | 800   |
| Umbrella    | quarter_2 | 224   |
| SleepingBag | quarter_2 | 936   |
| Umbrella    | quarter_3 | 379   |
| SleepingBag | quarter_3 | 93    |
| Umbrella    | quarter_4 | 611   |
| SleepingBag | quarter_4 | 875   |
+-------------+-----------+-------+
Explanation:
The DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter.

Approach Overview

Problem Overview: You receive a pandas DataFrame in wide format where multiple columns represent similar values (for example quarterly sales). The task is to reshape the table into a long format with three columns: the identifier column, a variable column (the original column names), and a value column.

Approach 1: Using Pandas Melt Function (O(n) time, O(n) space)

The most direct solution uses pandas.melt(), which is designed specifically for converting wide tables into long format. You specify the identifier column with id_vars, the columns to unpivot with value_vars, and provide names for the resulting variable and value columns. Internally, pandas iterates through each selected column and stacks the values into a new DataFrame. The time complexity is O(n), where n is the total number of cells being reshaped, and the space complexity is also O(n) because a new DataFrame is created. This approach is concise, readable, and the standard solution when working with pandas or DataFrame manipulation.

Approach 2: Manual Reshaping with Iteration (O(n) time, O(n) space)

If you want to understand what melt() does internally, you can manually reshape the data. Iterate through every row of the DataFrame and then iterate through each column that needs to be unpivoted. For each column, create a new record containing the identifier value, the column name (as the variable), and the corresponding cell value. Append these records to a list and convert the list into a new DataFrame. This approach also runs in O(n) time because each cell is processed exactly once, with O(n) additional space to store the reshaped rows. It’s useful when implementing similar transformations without relying on built-in helpers or when learning how data reshaping operations work internally.

Recommended for interviews: The expected solution is the pandas.melt() approach because it demonstrates familiarity with standard pandas transformations and keeps the implementation clean. Showing the manual iteration approach can still be valuable—it proves you understand how the reshape operation works under the hood—but production code and interview solutions typically favor the built‑in melt function.

Approach 1: Method 1: Using Pandas Melt Function

The pandas library offers a built-in method called melt which can directly transform data frames from wide to long format. This approach is particularly useful and efficient for reshaping data.

This solution uses the pandas.melt function to reshape the data from wide to long format. The id_vars parameter is used to identify the columns that should remain steady, while the var_name and value_name specify the names for the new dimension and its corresponding values.

Code

Python

Complexity

Time Complexity: O(n), where n is the number of elements in the DataFrame because the function iterates through each element.
Space Complexity: O(n) as a new DataFrame is created to store the reshaped data.

Try this approach in the editor →

Approach 2: Method 2: Manual Reshaping with Iteration

Here, we manually loop through the data, restructuring it by iterating over each record. This method provides a more granular approach compared to using built-in functions.

This solution constructs a new DataFrame by manually iterating over each entry in the original data. It collects product names, each quarter, and the associated sales figure. Each item is appended to a list that forms the structure of the new DataFrame.

Code

Python

Complexity

Time Complexity: O(p * q), where p is the number of products and q is the number of quarters in the data.
Space Complexity: O(n), where n is the total number of elements in the reshaped DataFrame.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Method 1: Using Pandas Melt Function

Time Complexity: O(n), where n is the number of elements in the DataFrame because the function iterates through each element.
Space Complexity: O(n) as a new DataFrame is created to store the reshaped data.

Method 2: Manual Reshaping with Iteration

Time Complexity: O(p * q), where p is the number of products and q is the number of quarters in the data.
Space Complexity: O(n), where n is the total number of elements in the reshaped DataFrame.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Using Pandas melt()O(n)O(n)Standard pandas workflow for reshaping wide tables into long format
Manual Reshaping with IterationO(n)O(n)When implementing reshaping logic without built-in helpers or for learning how melt works internally

Video Solution

Reshape Data Melt LeetCode 2890 • CuteLeetCrafter • 324 views views

Watch 3 more video solutions →

Frequently Asked Questions

Reshape Data: Melt Python solution
The Python solution typically uses pandas.melt(df, id_vars=[...], value_vars=[...], var_name='...', value_name='...'). This built-in function performs the reshape in O(n) time and produces a new DataFrame containing the identifier column, variable column, and value column.
Is Reshape Data: Melt easy or hard?
Reshape Data: Melt is considered an Easy problem. The challenge mainly checks whether you know the pandas melt() transformation and understand how wide-to-long reshaping works in tabular datasets.
How to solve Reshape Data: Melt in O(n)?
Use pandas melt() to unpivot the selected columns. Provide the identifier column with id_vars and the columns to transform with value_vars, then define names for the variable and value columns. The function scans each value exactly once, resulting in O(n) time complexity.
What is the best approach for Reshape Data: Melt?
The best approach is using the pandas melt() function. It directly converts a wide-format DataFrame into a long-format structure by specifying identifier columns and value columns. The operation runs in O(n) time and O(n) space where n is the number of values being reshaped, and it produces concise, readable code.
Is Reshape Data: Melt asked at Google/Amazon/Meta?
Data reshaping questions similar to this appear in data engineering and data science interviews at companies like Google, Amazon, and Meta. Candidates are often expected to know pandas transformations such as melt, pivot, and groupby for manipulating tabular datasets efficiently.
What data structure is used in Reshape Data: Melt?
The primary data structure is a pandas DataFrame. The reshape operation transforms the structure from wide format to long format by stacking column values into rows while preserving identifier columns.
What is the time complexity of Reshape Data: Melt?
The time complexity is O(n), where n represents the total number of cells involved in the reshape operation. Each value from the selected columns is processed once and moved into the resulting long-format DataFrame. Space complexity is also O(n) because a new DataFrame is constructed.

Ready to solve this problem?

Practice Reshape Data: Melt with our built-in code editor and test cases.

Practice on FleetCode