Reshape Data: Pivot - Solution & Explanation
Problem Statement
DataFrame weather
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| city | object |
| month | object |
| temperature | int |
+-------------+--------+
Write a solution to pivot the data so that each row represents temperatures for a specific month, and each city is a separate column.
The result format is in the following example.
Example 1:
Input:
+--------------+----------+-------------+
| city | month | temperature |
+--------------+----------+-------------+
| Jacksonville | January | 13 |
| Jacksonville | February | 23 |
| Jacksonville | March | 38 |
| Jacksonville | April | 5 |
| Jacksonville | May | 34 |
| ElPaso | January | 20 |
| ElPaso | February | 6 |
| ElPaso | March | 26 |
| ElPaso | April | 2 |
| ElPaso | May | 43 |
+--------------+----------+-------------+
Output:
+----------+--------+--------------+
| month | ElPaso | Jacksonville |
+----------+--------+--------------+
| April | 2 | 5 |
| February | 6 | 23 |
| January | 20 | 13 |
| March | 26 | 38 |
| May | 43 | 34 |
+----------+--------+--------------+
Explanation:
The table is pivoted, each column represents a city, and each row represents a specific month.
Approach Overview
Problem Overview: You receive tabular data where one column represents row identifiers, another represents column categories, and a third contains values. The task is to reshape the table so category values become columns while preserving the row identifier as the index.
Approach 1: Using Pandas Library in Python (Time: O(n), Space: O(n))
This approach relies on the built-in DataFrame.pivot() operation from the Pandas library. The key idea is that pivoting converts unique values from one column into new columns while aligning values using another column as the index. You pass the index column, the column that should become headers, and the value column. Pandas internally groups records and places each value in the correct row–column position. This is the most direct solution when working with tabular datasets in Python and avoids manual iteration. Prefer this when the environment already uses Python data analysis tools or when solving problems involving dataframe transformations.
Approach 2: Manual Aggregation and Restructuring in C (Time: O(n), Space: O(n))
Without high-level libraries, you reshape the data by iterating through each record and placing values into a newly structured table. Maintain a mapping from row identifier to row index and from category to column index. As you scan the dataset, perform a constant-time lookup and assign the value to the corresponding cell in a 2D structure. The core operations are iteration, lookup, and assignment. This mirrors how a pivot works internally and demonstrates how tabular reshaping can be implemented using basic structures like arrays or hash maps. This approach is useful in low-level environments where you must control memory layout or build the pivot table manually.
Recommended for interviews: The manual aggregation approach shows deeper understanding. Interviewers want to see how you transform row-based records into a structured grid using indexing or hashing. Mention that a library pivot operation exists, then explain the internal logic: iterate through records, map identifiers to indices, and populate a matrix-style structure. That demonstrates both practical awareness and algorithmic thinking.
Approach 1: Approach 1: Using Pandas Library in Python
This approach involves using the Pandas library in Python to pivot the data. Pandas offers a built-in pivot function that can easily transform your dataframe, setting the index, columns, and values appropriately.
This Python solution uses the Pandas library to pivot the data. The pivot function is called with the index set to 'month', columns set to 'city', and values set to 'temperature'. This means that each row is grouped by the 'month' field, and temperature data is organized into columns corresponding to each 'city'. Finally, reset_index() is applied to convert the row indices back into a column format.
Code
Python
Complexity
Time Complexity: O(n) - where n is the number of records in the dataframe, as we essentially have to process each record once.
Space Complexity: O(n) - the space used by the output structure is linear relative to the input.
Approach 2: Approach 2: Manual Aggregation and Restructuring in C
This approach involves manually restructuring the input data using arrays and dictionaries to simulate the pivot operation. This example is demonstrated in the C programming language.
This C code manually aggregates the input data into a new structure that acts as a pivot table. It uses arrays to store unique cities and a static array to hold the results. The cities are dynamically identified, and their index is used to populate the 'temperature' attribute of each month's data with appropriate values. The transformation is effectively a 'pivot' operation achieved by nested loops and simple data structures in C.
Code
C
Complexity
Time Complexity: O(m * n) - where m is the number of unique months and n is the number of unique cities, primarily driven by the nested looping.
Space Complexity: O(m*n) - the result table's space use is directly proportional to the input size, considering unique month and city combinations.
Approach 3: Default Approach
Code
Python
Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Using Pandas Library in Python | Time Complexity: O(n) - where n is the number of records in the dataframe, as we essentially have to process each record once. |
| Approach 2: Manual Aggregation and Restructuring in C | Time Complexity: O(m * n) - where m is the number of unique months and n is the number of unique cities, primarily driven by the nested looping. |
| Default Approach | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Pandas pivot() operation | O(n) | O(n) | Best when solving Python dataframe problems or performing quick data reshaping |
| Manual aggregation with maps and matrix | O(n) | O(n) | When implementing pivot logic without libraries or in low-level languages like C |
Video Solution
Reshape Data: Pivot. LeetCode 2889 • CuteLeetCrafter • 359 views views
Watch 3 more video solutions →Frequently Asked Questions
Reshape Data: Pivot Python solution
Is Reshape Data: Pivot easy or hard?
How to solve Reshape Data: Pivot in O(n)?
What is the best approach for Reshape Data: Pivot?
Is Reshape Data: Pivot asked at Google/Amazon/Meta?
What data structure is used in Reshape Data: Pivot?
What is the time complexity of Reshape Data: Pivot?
Ready to solve this problem?
Practice Reshape Data: Pivot with our built-in code editor and test cases.
Practice on FleetCodeTable of Contents
Practice this problem
Open in Editor