Skip to main content

Reshape Data: Pivot - Solution & Explanation

Easy6 min readAsked at: Amazon, Meta
Practice this problem

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.

Try this approach in the editor →

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.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
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.
Space Complexity: O(n) - the space used by the output structure is linear relative to the input.

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.
Space Complexity: O(m*n) - the result table's space use is directly proportional to the input size, considering unique month and city combinations.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Pandas pivot() operationO(n)O(n)Best when solving Python dataframe problems or performing quick data reshaping
Manual aggregation with maps and matrixO(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
In Python, the cleanest implementation uses pandas.DataFrame.pivot(index=..., columns=..., values=...). This converts row values into columns automatically and aligns data based on the specified index. The operation processes each row once, resulting in O(n) time complexity.
Is Reshape Data: Pivot easy or hard?
Reshape Data: Pivot is considered an easy problem. The challenge mainly involves understanding how pivot operations reorganize tabular data. With Pandas it requires a single function call, while a manual implementation involves straightforward iteration and indexing.
How to solve Reshape Data: Pivot in O(n)?
Iterate through the dataset once and place each value into its correct row and column position. Maintain mappings from row identifiers to row indices and category values to column indices. With constant-time lookups using a hash map, every record is inserted into the pivot table in O(1), producing overall O(n) time complexity.
What is the best approach for Reshape Data: Pivot?
The most practical solution uses the Pandas DataFrame.pivot() function, which reshapes tabular data by converting unique values from one column into new columns. It runs in O(n) time because each row is processed once while building the new structure. In interview settings, explaining the manual pivot logic using maps and a 2D table demonstrates stronger understanding.
Is Reshape Data: Pivot asked at Google/Amazon/Meta?
Data reshaping and pivot-style transformations commonly appear in data engineering and analytics interviews at companies like Google, Amazon, and Meta. Candidates are expected to understand how tabular data can be reorganized using indexing, grouping, or pivot operations.
What data structure is used in Reshape Data: Pivot?
The core structure is a 2D table or matrix representing the pivoted result. Hash maps are often used to map row identifiers and column categories to indices for constant-time placement of values during iteration.
What is the time complexity of Reshape Data: Pivot?
The typical solution runs in O(n) time where n is the number of rows in the dataset. Each record is processed once to determine its position in the reshaped table. Space complexity is also O(n) since a new table structure is created to store the pivoted data.

Ready to solve this problem?

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

Practice on FleetCode